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
-INT_MIN
is already a positive number, so it is fine to assign it touint64_t up2
?Why it seems to be ok to assign
-INT_MIN
touint32_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)???