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
- In C, what value does the expression (x = 5) have?
- 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).
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
- A grading program runs: if score >= 90 give A; elif score >= 80 give B; elif score >= 70 give C; else give F.…
- With short-circuit evaluation, in the expression A or B, if A is true then B is still always evaluated.
- Sort each operator by its role.
- if x = 5 is a common bug in languages where it is legal, while if x == 5 is what was meant. Why is the…