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

Python makes if x = 5 a syntax error while C compiles it happily. What is C's version actually doing?

Hints
  1. In C, what value does the expression (x = 5) have?
  2. Ask what error message the programmer receives. Then ask what the variable now holds.
Show the answer

D. Assigning 5 to x and taking the branch, since 5 is truthy

Why

Assignment is an expression in C, so it yields 5, the branch always runs, and x has been overwritten as a side effect of a test. No error is reported anywhere, which is why Python made assignment a statement, Java requires a boolean condition, and C programmers learned to write 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