Back to questionsWhy does
JuniorDebuggingVery common
Why does if (x = 0) take the wrong branch?
With x starting at 5, this prints nonzero, x=0 — both parts surprise the author.
int x = 5;
if (x = 0) {
std::cout << "zero";
} else {
std::cout << "nonzero, x=" << x;
}Find and fix the bug.
x = 0 is assignment, not comparison: it stores 0 into x and the expression evaluates to 0 (false), so the else runs and x is now 0. The author meant ==. Compilers warn with -Wparentheses; some style guides write if (0 == x).
- Reading
=as==inside a condition - Expecting a compile error rather than a silent wrong branch
- Not enabling -Wparentheses to catch the typo
- Why does writing
if (0 == x)turn this typo into a compile error? - What does the value of an assignment expression equal in C++?