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?
- A5 6 6
- B5 7 7
- 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.