Why does this unsigned int contain more data than memory has?

An unsigned int can only store 32 bits of data. Why doesn't the compiler report an error when I assign it a greater value than what it can hold?

I tried other different values ​​and did not give errors.

 int main() { unsigned int mem = 0x89678456543454345934; cout << mem; return 0; } 
+6
source share
1 answer

This is because 0x89678456543454345934 greater than std::numeric_limits<unsigned_int>::max() . However, unsigned types wrap their maximum value, so if the right side is a representable integer type, you have well-defined behavior. In this case, the result is 0x89678456543454345934 mod std::numeric_limits<unsigned_int>::max .

EDIT

The right side of your job is an integer literal . To represent it, the compiler uses the first type (ordered by its size), in which an integer literal can correspond. If there is no such type, then the program is poorly formed . The decimal value of your constant:

 648873758694578209446196L 

On my machine for clang ++ and g ++ std::numeric_limits<unsigned long long>::max() there is 18446744073709551615 , which is less than your constant. It seems that your program is then badly formed if the compiler does not use more than 64 bits to represent an unsigned long long , which I really doubt. As @juanchopanza remarked, clang ++ refuses to compile the error code

error: integer constant greater than largest unsigned integer type

g ++, however, goes ahead and compiles it, giving only a warning

warning: a large integer is implicitly truncated to an unsigned type

The warning is rather confusing as it relates to the right side and not to further conversion to unsigned int for which you get

warning: a large integer is implicitly truncated to an unsigned type [-Woverflow]

On my machine, std::numeric_limits<unsigned int>::max() is 4294967295 , and therefore 648873758694578209446196L % 4294967295 is 3633002191L . However, when I run your program, I get 1412716852 . This is because the program is poorly formed, and, unfortunately, the compiler does not emit an error (it is not required by the standard), but only a warning.

+12
source

Source: https://habr.com/ru/post/987530/


All Articles