Mathematics I / Conditionals and Boolean Logic
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
  1. Ask what happens to arr[i] when i is past the end and the expression is evaluated anyway.
  2. 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.

Read the lesson: Conditionals and Boolean Logic →

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.

More questions on Conditionals and Boolean Logic