When I run the following code under Windows7 x64, compiled with GCC of MinGW, the result seems to be underflowed:
cout<<-2147483648 ; //Output: 2147483648
but when I assigned it to a integer variable, or just simply convert it to the int type :
cout<<(int)-2147483648 ; //Output: -2147483648
So, what’s wrong with the previous version of my code? Istn’t it the type int? or what the lower bound the Integer is exactly?
Many thanks.
2147483648 doesn’t fit into an int or a long on your system, so it’s treated as a constant of type unsigned long. (Edit: as ouah pointed out in the comments, it’s undefined behaviour in standard C++, but your compiler accepts it as an extension.) Negating an unsigned integer value is possible, but results in another unsigned integer value, never a negative number. Negating 2147483648UL produces 2147483648UL (assuming, as is the case on your system, that unsigned long is a 32 bit type).
Casting that to
intproduces an implementation-defined result, commonly the result you see, but not necessarily. You can get the result you want without any conversions by writing -2147483647 – 1.