Practice question · Multiple choice
if (i < len && arr[i] > 0) is safe, and swapping the two conditions can crash. Why does the order of a boolean test matter when AND is commutative?
Hints
- Ask what happens to
arr[i]when i is past the end and the expression is evaluated anyway. - The truth table for AND says nothing about order. What supplies the order?
Show the answer
A. Because short-circuit evaluation stops at the first false
Why
Logically A ∧ B equals B ∧ A; operationally the language evaluates left to right and stops early, so the guard protects the access. It is a language guarantee layered on top of the logic, and it is why side effects inside boolean expressions are such a reliable source of bugs.
Practise Conditionals and Boolean Logic
The app has 7 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.