Computer Science I / Conditionals and Logical Branching
Practice question · Multiple choice

if x = 5 is a common bug in languages where it is legal, while if x == 5 is what was meant. Why is the mistake so easy to make and so hard to spot?

Hints
  1. In C, what does the expression (x = 5) evaluate to?
  2. Ask what error message the programmer receives.
Show the answer

B. Because assignment is an expression, so the mistaken version compiles and runs.

Why

In C and its relatives assignment is an expression whose value is the assigned value, so if (x = 5) assigns, evaluates to 5, and takes the branch, silently, with nothing to report. Language designers have responded in several ways, which shows how serious it is: Python makes assignment a statement, Java demands a boolean, and C programmers invented if (5 == x).

Read the lesson: Conditionals and Logical Branching →

Practise Conditionals and Logical Branching

The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Conditionals and Logical Branching