• Advertisement
Sign in to follow this  

static_cast problem

This topic is 2934 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

since few minutes I tried practice "static_cast" to convert from short variable to int variable, I wrote this trivial program to print the variables before using static_cast and after using static_cast in console screen, but the variable not converted..! here is my code.. //EGYPT population | static cast #include <iostream> using namespace std; int main() { short shortEgyPop = 80000000; shortEgyPop = (shortEgyPop * 10)/10; cout << "shortEgyPop = " << shortEgyPop << endl; shortEgyPop = 80000000; shortEgyPop = (static_cast<int>(shortEgyPop)*10)/10; cout << "shortEgyPop = " << shortEgyPop << endl; return 0; } And the following image includes my output, the first answer must be 80,000,000 not -19456 ..? http://www.daniweb.com/forums/attachment.php?attachmentid=13505&d=1265280730

Share this post


Link to post
Share on other sites
Advertisement
Your link is accessible to members only.

Your problem may be that a short is too small to hold the number 80000000 in the first place. A short int (signed) can generally hold from −32,768 to +32,767. Any larger number will 'wrap' around, which is why you might be getting a negative number.

Share this post


Link to post
Share on other sites
Also, static_cast<> does not change the type of the variable on the left side of the assignment operator, but only of the something that is enclosed in the parens, static_cast<>(here).

That is, after

short foo;
foo = static_cast<int>(3);


foo will still be of type short integer.

Share this post


Link to post
Share on other sites
Say I give you a watermelon, a small box, and a big box. The watermelon will fit into the big box, but not into the small box.

What you are doing here

shortEgyPop = 80000000;
shortEgyPop = (static_cast<int>(shortEgyPop)*10)/10;
cout << "shortEgyPop = " << shortEgyPop << endl;


is: you cut off a tiny piece of the watermelon that will fit into the small box, and put it in. Then you take the piece out, put it into the big box, scribble on it, and put it back into the small box. Then you look at the scribbled-on piece in the small box and are surprised that (a) the watermelon is not intact and (b) the small box is still small. Putting the piece of watermelon into the big box cannot make the small box into a big box, and it can't make the piece into a whole watermelon again.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement