C语言中移位和算术运算符优先级的混淆

时间:2018-12-28 17:31:04

标签: 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,但第一个输出为零。为什么会这样呢?

3 个答案:

答案 0 :(得分:2)

如果您看到例如this operator precedence table中,您会发现+运算符的优先级高于shift运算符。

这意味着表达式x >> 2 + z << 1实际上等于(x >> (2 + z)) << x

答案 1 :(得分:2)

如果查看C的operator precedence table,您会发现加法运算符+的优先级高于左移运算符和右移运算符<<和{{1} }。

所以这个:

>>

与:

y=x>>2 +  z<<1;

您需要像添加括号一样来更改子表达式的求值顺序。

答案 2 :(得分:2)

y = (x >> (2 + z) << 1);

评估为

y=x>>2 +  z<<1; //this gives the output 0

因为运算符优先。请参见operator的手册页;它说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 的优先级最高。