C Programming Basics

int i = 5;
int a = i++;
int b = ++i;
printf("%d %d %d\n", a, b, i);

Which of the following is the output when the code above, which uses prefix and postfix ++, is executed?

  1. A5 6 6
  2. B5 7 7
  3. C6 7 7
Show answer and explanation

Answer: B. 5 7 7

Postfix i++ uses the value before the increment as the value of the expression and then increases i by 1. So a gets 5 and i becomes 6. Prefix ++i first increases i by 1 and then uses the new value as the value of the expression, so i becomes 7 and b also gets 7. The output is "5 7 7".

  • A. Even with i++, i itself increases to 6. This is the value obtained if i is thought to stay at 5.
  • B. Correct. a is 5, the value before the increment, and b and i are 7 after two increments.
  • C. The value of postfix i++ is 5, the value before the increment, so a is not 6.
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. Which of the following is the output when the code above, with = written in the condition of an if statement, is executed?
  2. 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?
  3. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above is executed?
  4. 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?
  5. unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?