Interview Question
Country: United States
the first exp can be written as (x++)/(++x) //precedence of operator
now from right the value of x becomes 2 but the value of x on the left does not change as its a post fix so we have x/x resulting in 1 now the postfix takes effect so value becomes 2
the 2nd exp same thing follows (++x)/(x++)
from right being a post fix value remains one, but in the left value chages to 2
so x/x results in 2/2 i.e 1 and with post fix x again becomes 2
Undefined Behaviour - Explained very well in "C FAQ's" by Steve Summit.
Please refer this question (question No. 3.1)
" Q: Why doesn't this code:
a[i] = i++;
work?
Ans - The subexpression i++ causes a side effect--it modifies i's value--which leads to undefined behavior since i is also referenced elsewhere in the same expression. There is no way of knowing whether the reference will happen before or after the side effect--in fact, neither obvious interpretation might hold "
for x=x++/++x;
its evaluated in this order:
1.++x makes x =2.
2.now since x++ is post increment, the exp becomes x/x++ ie 1/2 = 0(since x is int).
3.now assignment operator(=) has low precedence than post increment(++), x=1 is incremented to 2 and then its assigned to x.
for x=++x/x++;
its evaluated in this order:
1.++x increments x =2
2.now exp becomes x = 2/(1)++ which is evaluated to 2/1 = 2
3.x is still 1 and its incremented to 2(due to post increment) and assigned to x making it 2.
its very simple ........in evaluation it will take first only expression then increment operator means
for both the expressions x=x/x now it will put the value of x =2 because of pre increment operator ..... so we will get the result 1 and then again incremented by 1 because of post increment......
this is undefined behaviour...
- topc July 12, 2012