直接将左移操作的结果分配给变量和C中的左移分配操作有什么区别?

18 c bit-shift relational-operators

在下面的表达式中,左移操作的结果被赋值给变量i.

int i;
i = 7 << 32;
printf("i = %d\n",i);
Run Code Online (Sandbox Code Playgroud)

在下面的表达式中,执行左移位分配操作.

int x = 7;
x <<= 32;
printf("x = %d\n",x);
Run Code Online (Sandbox Code Playgroud)

上述两种表达都给出了不同的结果.但是以下两个表达式并不相同.两者都给出了相同的结果.那么上述表达式返回不同值的原因是什么呢?

int a;
a = 1 + 1;
printf("a = %d\n",a);

int b = 1;
b += 1;
printf("b = %d\n",b);
Run Code Online (Sandbox Code Playgroud)

msc*_*msc 26

C标准说:

如果右操作数为负数,或者大于或等于左表达式类型中的位数,则结果为undefined.

因此,它是未定义的行为,因为int它通常是32位大小,这意味着只有0通过31步骤才能很好地定义.

  • @MarcSchütz你错了,请阅读C标准 (2认同)

Shu*_*vam 5

我同意Cody Gray的评论.对于将来会在这里结束的人来说,解决这种歧义的方法是使用unsigned long long.

unsigned long long int b = 7ULL<<32; // ULL here is important, as it tells the compiler that the number being shifted is more than 32bit.

unsigned long long int a = 7;
a <<=32;
Run Code Online (Sandbox Code Playgroud)

  • 当考虑通过"n位"移动来推荐使用`stdint`中明确确保位长的`int64_t`,`uint64_t`等时,可能会很勤奋 (3认同)