Why -INT_MIN is NOT 2147483648 for uint64_t type

  • A+

I understand the results of p. Could someone please explain why up2 (uint64_t type) != 2147483648 but up (uint32_t type) == 2147483648?

Some mention that assigning -INT_MIN to unsigned integer up2 will cause overflow, but

1) -INT_MIN is already a positive number, so it is fine to assign it to uint64_t up2?

2) Why it seems to be ok to assign -INT_MIN to uint32_t up? It produces correct result as 2147483648.

#include <iostream> #include <climits>  using namespace std;  int main() {     int n = INT_MIN;     int p = -n;     uint32_t up = -n;     uint64_t up2 = -n;      cout << "n: " << n << endl;     cout << "p: " << p << " up: " << up << " up2: " << up2 << endl;     return 0; }  Result: n: -2147483648 p: -2147483648 //because -INT_MIN = INT_MIN for signed integer up: 2147483648 //because up is unsigned int from 0 to 4,294,967,295 (2^32 − 1) and can cover 2147483648  up2: 18446744071562067968  //Question here. WHY up2 != up (2147483648)???  


The behaviour of int p = -n; is undefined on a 2's complement system (accepting that you have a typo in your question; INT_MAX is always odd on such a system), due to your overflowing an int type. So your entire program is undefined.

This is why you see INT_MIN defined as -INT_MAX - 1 in many libraries.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: