c/c++ left shift unsigned vs signed

后端 未结 5 1805
庸人自扰
庸人自扰 2021-02-14 13:53

I have this code.

#include 

int main()
{
    unsigned long int i = 1U << 31;
    std::cout << i << std::endl;
    unsigned lon         


        
5条回答
  •  灰色年华
    2021-02-14 14:33

    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.

提交回复
热议问题