这个按位操作如何工作?

时间:2016-05-16 13:24:07

标签: c++

这段代码让我很困惑:

bool b = 8 & 7 == 0; //b == false
std::cout << 8 & 7; //Outputs 0

为什么这样做?

4 个答案:

答案 0 :(得分:8)

http://en.cppreference.com/w/c/language/operator_precedence

==之前执行/评估

&,所以你得到:

bool b = 8 & 7 == 0; //==>

//  7==0 --> 0
//  8 & 0 --> 0 (which is 'false')
//  ==> b is false

要获得您的期望,只需添加()

bool b = (8 & 7) == 0; // will be evaluated as 'true'

答案 1 :(得分:5)

因为==优先于&。所以,你的表达式相当于:

( 8 & (7==0))

等于0.

答案 2 :(得分:1)

你的问题是表达式:

8 & 7 == 0;

等于:

8 & ( 7 == 0 );

所以要明确使用括号:

( 8 & 7 ) == 0;

如果您不满意评估顺序,则应始终使用括号。

答案 3 :(得分:0)

第一行已被掩盖, 对于第二行,因为8 = 1000和7 = 0111,结果为0,预期是