我遇到了一种行为,我没想到在无符号整数上使用按位运算。我会切入我的榜样。
unsigned int a = 0;
unsigned int b = 0;
std::printf("a & b: %u\n", a & b);
std::printf("a == b: %i\n", a == b);
std::printf("a & b == a: %i\n", a & b == a);
上面的代码产生以下输出:
a & b: 0
a == b: 1
a & b == a: 0
最后一行令我感到困惑。由于a & b == a
和true
,我不应该a & b == (unsigned int)0
评估为a == (unsigned int)0
吗?
答案 0 :(得分:7)
您之所以得到此行为,是因为您在C operator precedence table ==
之前没有意识到&
。事实上,一个好的编译器会立即警告你你的代码:
t.cpp:10:35: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
std::printf("a & b == a: %i\n", a & b == a);
^~~~~~~~
t.cpp:10:35: note: place parentheses around the '==' expression to silence this warning
std::printf("a & b == a: %i\n", a & b == a);
^
( )
t.cpp:10:35: note: place parentheses around the & expression to evaluate it first
std::printf("a & b == a: %i\n", a & b == a);
^
( )
确保您的警告已开启,例如g++ -Wall -Wextra -Werror
。
答案 1 :(得分:5)
你应该写:
(a & b) == a
现在您从a & b
will be evaluated first获得1:
(a & b) = 0
,0 == 0
为1。
在您的情况下,a & b == a
评估为a & (b == a)
,b == a
为1,a & 1
为0。
答案 2 :(得分:5)
由于==
's precedence over &
,a & b == a
被评估为a & (b == a)
(而不是(a & b) == a
,因为您看起来已经预期了。)