The flag that is always true
A easy Java puzzle in the logic and control flow family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 4. Play this one as a puzzle without the answer.
What is wrong
A single = assigns true to failed and the assignment expression evaluates to true, so the branch always runs. The compiler accepts it because a boolean assignment is a boolean expression.
The fix
How to avoid it next time
Write if (flag) rather than if (flag == true), which removes the chance of the missing second equals sign.
Want the background? Read Loops, labels and do-while in the Java concepts library.
About logic and control flow
Operator precedence, missing break statements, short-circuit evaluation and loop conditions that never change are simple to write and tiring to spot after a long day of reviews.
In code review: Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
More puzzles in this family
Frequently asked questions
What is the bug in "The flag that is always true"?
A single = assigns true to failed and the assignment expression evaluates to true, so the branch always runs. The compiler accepts it because a boolean assignment is a boolean expression. The faulty line is line 4: if (failed = true) {
How do I fix it?
Replace it with: if (failed) {. Write if (flag) rather than if (flag == true), which removes the chance of the missing second equals sign.
How do I catch logic and control flow in code review?
Read conditions out loud with explicit parentheses, check every switch branch for break or return, and make sure each loop makes progress toward its exit.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.