提问人:Ankit Karna 提问时间:12/29/2018 最后编辑:Ankit Karna 更新时间:12/31/2018 访问量:149
混淆了 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,但第一个输出为零。为什么会这样?
答:
2赞
Some programmer dude
12/29/2018
#1
例如,如果您看到此运算符优先级表,您将看到运算符的优先级高于移位运算符。+
这意味着表达式实际上等于 。x >> 2 + z << 1
(x >> (2 + z)) << x
2赞
dbush
12/29/2018
#2
如果查看 C 的运算符优先级表,您会发现加法运算符的优先级高于左移位和右移位运算符和 。+
<<
>>
所以这个:
y=x>>2 + z<<1;
等同于:
y = (x >> (2 + z) << 1);
您需要添加括号,就像更改子表达式的计算顺序一样。
2赞
Achal
12/29/2018
#3
这
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
因为运算符优先级。参见操作手册页;它说比轮班操作员具有更高的优先级。+
而这个
y=(x>>2) + (z<<1); //this gives the output 8
定义明确; 具有最高优先级。()
评论
1赞
Ankit Karna
12/29/2018
明白了。谢谢你的帮助
评论