(int) 4294967295.0 = 2147483647?

Code example:

#include <stdio.h>

int main() {
    printf("%d", (int)4294967295.0);
    return 0;
}

This prints 2147483647 on code code ( http://codepad.org/yDCqFdTT ) and -2147483648 in vs2012 settings. -1 expected. However, converting 4294967295.0 to an unsigned integer gives -1.

What's happening? How can I safely convert my double to int? This type of error is outside the range of rounding errors.

+4
source share
3 answers

According to project N1256 (C99) and section 6.3.1.4, you invoke undefined behavior:

6.3.1.4 Real floating and integer

  • , _Bool, (.. ). , undefined. 50)

  • , , . , , , , , . , , undefined.

50) , , , . , (-1, Utype_MAX+1).

+8

undefined : int, .

( int 32 ) , int. , , / , .

- boost::numeric_cast .

0

The conversion from double to int first ignores the fractional part, giving 4294967295. This number is not represented in the int type, so the result is undefined behavior. The result can be any number. Your computer may crash or explode. Anything can happen because your code causes undefined behavior.

0
source

All Articles