Very Basic C++ Problem Understanding static_cast

KAMAZON

Golden Member
Apr 4, 2001
1,300
0
76
www.alirazeghi.com
Hello fellow Anandtechers, I have a problem figuring out static_casting from my book which only tells me to understand how this example works, yet doesn't provide me the steps to figure it out. Go figure. I looked on wikipedia but couldn't figure it out either. Perhaps one of you can shine some light on this topic:

static_cast<int>(7.8 +
static_cast<double(15/2)) = static_cast<int>(7.8 + 7.0)
= static_cast<int>(14.8)
=14


ok so this is doing the exact opposite of what I would think it will do. The first line:

static_cast<int>(7.8 + makes me assume that "OK This is going to turn the floating point number 7.8 into a integer of 7.

Then the 2nd line does the opposite of what I would expect as well. Mainly I think
static_cast<double(15/2)) would give me Double floating point number which in this case would only be 7.5. WRONG. Apparently it's only 7.

Finally at the very end, the number is displayed as a integer.

Any ideas? Thanks.


edit:


Here is another basic problem I have with understand static_cast which I think might be a root problem i'm occuring.

static_cast<double>(15) / 2 = 7.5
static_cast<double>(15 / 2) = 7



Why does the .5 get dropped if the static cast is performed with numbers in paranthesis after the word <double>? Listed below is a more complex example.

cout << "static_cast<int>(7.8 + static_cast<double>(15) / 2) = "
<< static_cast<int>(7.8 + static_cast<double>(15) / 2 )
<< endl;
This gives me a reply of:
static_cast<int>(7.8 + static_cast<double>(15) / 2) = 15



cout << "static_cast<int>(7.8 + static_cast<double>(15 / 2)) = "
<< static_cast<int>(7.8 + static_cast<double>(15 / 2 ))
<< endl;
This gives me a reply of:
static_cast<int>(7.8 + static_cast<double>(15 / 2)) = 14


If these could be explained as well I'd appreciate it. I understand that the order of precedence is changed but I'm not sure how that is affecting this outcome. Thanks again.
 

mundane

Diamond Member
Jun 7, 2002
5,603
8
81
15/2 is int/int, which results in an int. Casting to a double would result in 7.0.

(int)(7.8 + (double)(15) /2)
(int)(7.8 + (15.0)/2)
(int)(7.8 + 7.5)
(int)(15.3)
15

(int)(7.8 + (double)(15/2))
(int)(7.8 + (double)(7))
(int)(7.8 + 7.0)
(int)(14.8)
14
 

aCynic2

Senior member
Apr 28, 2007
710
0
0
static_cast<int>(7.8 +
static_cast<double(15/2)) = static_cast<int>(7.8 + 7.0)
= static_cast<int>(14.8)
=14

Mind you, I don't know C++ very well, but if I remember casting (but I've never encountered static casting before) and order of operations, what's inside the parenthsis take precedence over the casting. Thus, the 7.8 is added to the 7.0 before the whole is cast as an integer, and the 15/2 is calculated as an integer before being cast as a double.

I hope this is true and helpful.