587 views
6 votes
6 votes
int i;
i=5;
i=i++;
printf("%d",i);



What is output of this program??

Is it undefined behavior ?? Why??

3 Answers

Best answer
7 votes
7 votes

That is what is called as undefined behavior of C .

i = i++

Here, we are modifying the same value twice , which is not allowed .

Hence, if we talk about this,

a[i] = i++

which is incrementing , i.e, changing i and even using it at the same time, which is really not allowed.

Hence, it all depends on the compiler.


Run this simple code 

i = 5;

i = i++;


some compilers will give 5 and some give 6.


Refer ==> http://www.geeksforgeeks.org/sequence-points-in-c-set-1/

http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points

selected by
0 votes
0 votes
its output should be 6 and it is not undefined beahviour

i=i++ is equvt to i=i+1 ;

in next line i is printed as 6 so no problem

PS undefined behaviour comes into picture when i is incremented more than once in single statement

like i=++i++  + i++ etc
0 votes
0 votes
Modifying the same variable more than once  within a single expression is Undefined behaviour.(diffrent compiler do it differently).

Here Value of i can be {5 or 6}

 

Some other Undefined behaviour:-

1. f()+g();

2.a[i]=i++;

3.y=x++ * ++x

Note f(x),g(x) is not undefined behaviour bcz ,(comma) operator introduces a sequence point that f(x) then g(x)

Related questions

1 votes
1 votes
1 answer
1
papesh asked Aug 16, 2016
491 views
What is output of the program?? And why??
1 votes
1 votes
2 answers
2
papesh asked Aug 11, 2016
419 views
Suppose in my c program having infinite loop and it is printing garbase values ... Because of some logical errors... So till what time it will run and why ??? Will it giv...