Why it is different between -2147483648 and (int)-2147483648

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 int produces 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.

Leave a Comment