C Programming Basics
int x = 5;
if (x = 0)
printf("zero ");
else
printf("nonzero ");
printf("%d\n", x);Which of the following is the output when the code above, with = written in the condition of an if statement, is executed?
- Azero 0
- Bnonzero 5
- Cnonzero 0
Show answer and explanation
Answer: C. nonzero 0
x = 0 in the if condition is an assignment, not the comparison ==. x becomes 0 and the value of the assignment expression is also 0, so the condition is false and "nonzero" from the else branch is printed. The following printf prints x, which the assignment made 0. With gcc, -Wall gives a warning for this way of writing, so keeping warnings enabled makes the mistake easier to notice.
- A. The value of the assignment expression is the assigned 0, so the condition is false and "zero" is not printed.
- B. x = 0 is an assignment, not a comparison, so x has been changed to 0.
- C. Correct. 0 is assigned to x, and the condition is false.