Quiz Entry - updated: 2026.07.10
What is the classic = vs == bug in C, and how can you use it intentionally?
Writing = (assign) where you meant == (compare) silently assigns and then tests the result for non-zero — it compiles fine but does the wrong thing.
// Bug: This ASSIGNS b to a, then checks if result is non-zero
if (a = b) c = 0;
// This is equivalent to:
a = b;
if (a != 0) c = 0;
The problem: Compiles without error, does something completely different!
Intentional use (useful idiom):
// Assign and check in one step
if ((c = open("f.txt")) < 0)
printf("Can't open file");
// Read until EOF
while ((c = getchar()) != EOF) {
process(c);
}
Best practice when intentional:
- Double parentheses:
if ((a = b))signals intent - Explicit comparison:
if ((a = b) != 0)
Compiler help: Use -Wall -Werror to catch accidental assignments in conditions.