in Programming retagged by
1 vote
1 vote

Output of following program

int main() 
int i=5; 
printf("%d %d %d", i++,i++,i++); 
return 0; 
  1. $7\:6\:5$
  2. $5\:6\:7$
  3. $7\:7\:7$
  4. Compiler Dependent
in Programming retagged by

2 Answers

4 votes
4 votes
Best answer

Compiler dependent. 


A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because they are a core concept for determining the validity and, if valid, the possible results of expressions. Adding more sequence points is sometimes necessary to make an expression defined and to ensure a single valid order of evaluation.

The compiler will evaluate printf's arguments in whatever order it happens to feel like at the time. It could be an optimization thing, but there's no guarantee: the order they are evaluated isn't specified by the standard, nor is it implementation defined. There's no way of knowing.

But what is specified by the standard, is that modifying the same variable twice in one operation is undefined behavior; ISO C++03, 5[expr]/4:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

So D is correct.


selected by
0 votes
0 votes
Answer is A

7 6 5


i++ is post increment so


1 comment

correct, I would also add that printf function assigns values from right to left. Hence the answer is 7,6,5.


option A

Related questions