in Programming in C retagged by
1,014 views
2 votes
2 votes

Output of following program

#include<stdio.h> 
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 in C retagged by
by
1.0k views

2 Answers

5 votes
5 votes
Best answer

Compiler dependent. 

Why?

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.

Ref: https://en.wikipedia.org/wiki/Sequence_point

https://stackoverflow.com/questions/1270370/printfd-d-d-n-a-a-a-output

selected by
0 votes
0 votes
Answer is A

7 6 5

i=5

i++ is post increment so

(i++,i++,i++)=(7,6,5)

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
0
0
Answer:

Related questions