09 Beginner The Hundred
The Bit Test That Never Fires
a parity check that has already made up its mind
#include <iostream>
void report(int x) {
if (x & 1 == 0)
std::cout << x << " is even\n";
else
std::cout << x << " is odd\n";
}
int main() {
report(4);
report(7);
}
Run it. Which number is even?
Why¶
== binds tighter than &, so the condition parses as x & (1 == 0) — never the
(x & 1) == 0 you meant. 1 == 0 is false, which converts to 0, and x & 0 is 0
for any x, so the if is permanently false and the mask is never actually applied. The
bitwise operators &, ^ and | sit below the comparisons in the precedence table:
a C inheritance from the days before && and || existed, when & doubled as the
logical AND. Shifts have the same weakness — 1 << 1 + 2 is 1 << 3, which is 8.
GCC catches it with -Wall: -Wparentheses says "suggest parentheses around comparison
in operand of &". (-Wextra alone stays silent.)
The fix¶
Parenthesize the mask — it costs two characters:
Takeaway: &, | and ^ bind looser than == — parenthesize every bit test you
compare against something.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo