What is the output/behavior of the following C program? #include<stdio.h> int…
2020
What is the output/behavior of the following C program?
#include<stdio.h>
int main()
{
int i = 5;
printf("%d %d %d", i++, i, ++i);
return 0;
}
Answer: C. Undefined behavior — Concept: In C, a sequence point marks a place where all side effects of prior evaluations are guaranteed complete before evaluation continues. Between two…
- A.
7 6 6
- B.
6 7 8
- C.
Undefined behavior
- D.
5 6 7
Attempted by 1517 students.
Show answer & explanation
Correct answer: C
Concept: In C, a sequence point marks a place where all side effects of prior evaluations are guaranteed complete before evaluation continues. Between two sequence points, modifying the same scalar object more than once, or modifying it while also reading its value for something other than computing the new stored value, is undefined behavior. The C standard also leaves the order in which a function call’s arguments are evaluated unspecified — a compiler may evaluate them left-to-right, right-to-left, or in any other order, and may schedule the associated side effects at different points.
The call is printf("%d %d %d", i++, i, ++i); with i initialized to 5.
All three arguments — i++, i, and ++i — are evaluated as part of setting up the same function call; the only sequence point here occurs right before the actual call, after every argument has been evaluated.
i++ modifies i (post-increment), ++i also modifies i (pre-increment), and the middle argument reads i directly — that is two modifications and one plain read of the same object across the three argument evaluations, with no sequence point separating them from each other.
Because no sequence point separates these evaluations, the compiler is free to choose any order among the three arguments and to apply the two increments at any point relative to the plain read — the standard places no obligation on what value the plain i sees or in which order the increments occur.
Cross-check: Different compilers, and even the same compiler under different optimization settings, are free to print different values for this exact program without violating the standard, because the standard simply does not define an outcome here. Assuming one specific evaluation order — say, strict left-to-right with each side effect applied immediately — only reproduces ONE of the many results a conforming compiler could legally produce; it does not establish what "the" output is.
Therefore, the only defensible classification for this program is undefined behavior — not any specific triplet of printed numbers.
Explore the full course: Iocl Engineers Officers Grade A Paper 2