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?

  1. Azero 0
  2. Bnonzero 5
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. The code above was written to check whether bit 2 of the register value reg is 1. Which of the following is the result when it is executed?
  2. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above is executed?
  3. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?
  4. unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?
  5. uint8_t is an 8-bit unsigned integer type and int is 32 bits. Which of the following is the result when the code above is executed?