![](/img/trans.png)
[英]Are the shift operators (<<, >>) arithmetic or logical in C?
[英]Confusion with precedence of shift and arithmetic operators in C
我不熟悉C语言中的运算符,对它们感到困惑。
int x = 2, y, z = 4;
y = x>>2 + z<<1; // this gives the output 0
y = (x>>2) + (z<<1); // this gives the output 8
我期望两个输出均为8,但第一个输出为零。 为什么会这样呢?
如果您看到例如该运算符优先级表,您将看到+
运算符的优先级高于shift运算符。
这意味着表达式x >> 2 + z << 1
实际上等于(x >> (2 + z)) << x
。
如果查看C的运算符优先级表 ,您会发现加法运算符+
优先级高于左移运算符和右移运算符<<
和>>
。
所以这:
y=x>>2 + z<<1;
是相同的:
y = (x >> (2 + z) << 1);
您需要像添加括号一样更改子表达式的求值顺序。
这个
y=x>>2 + z<<1; //this gives the output 0
评估为
y=( x>>(2 + z)) << 1;
^^^^this performed first i.e 6, next x>>6 which is 0 and then 0<<1 is zero
由于运算符的优先级。 参见操作员手册页; 它说+
优先级高于shift运算符。
和这个
y=(x>>2) + (z<<1); //this gives the output 8
定义明确; ()
具有最高优先级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.