I have this code.
#include
int main()
{
unsigned long int i = 1U << 31;
std::cout << i << std::endl;
unsigned lon
The literal 1
with no U
is a signed int
, so when you shift << 31
, you get integer overflow, generating a negative number (under the umbrella of undefined behavior).
Assigning this negative number to an unsigned long
causes sign extension, because long
has more bits than int
, and it translates the negative number into a large positive number by taking its modulus with 264, which is the rule for signed-to-unsigned conversion.