c++ - Strange behavior when static casting from a big double to an integer -


here 's simple code:

int main() {   double d1 = 10000000000.0;   const double d2 = 10000000000.0;    cout << static_cast<int>(d1) << endl;   cout << static_cast<int>(d2) << endl;   cout << static_cast<int>(10000000000.0) << endl; } 

the output is:

-2147483648 2147483647 2147483647 

this surprised me grealy. why positive double casted negative int?

i'm using g++: gcc version 4.4.3 (ubuntu 4.4.3-4ubuntu5).

casting double int when int isn't big enough hold value yields undefined behaviour.

[n3290: 4.9/1]: prvalue of floating point type can converted prvalue of integer type. conversion truncates; is, fractional part discarded. the behavior undefined if truncated value cannot represented in destination type.

this behaviour derived c:

[c99: 6.3.1.4/1]: when finite value of real floating type converted integer type other _bool, fractional part discarded (i.e., value truncated toward zero). if value of integral part cannot represented integer type, behavior undefined.

for you, int isn't big enough.

  • and, in first case, happens result in sign bit being set.
  • in second , third cases, again you, it's optimisations happen result in different behaviour.

but don't rely on either (or, indeed, any) behaviour in code.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -