Interview Question
Country: United States
well if we convert above statement into instruction set then it ll execute as follow:
eg: Add a,b,c (in instruction set)
i.e add value at address of b with value at address of c and store at address of a. Remember address plays imp role here.
Now
x=x++/++x
It will be converted as follows:
(x++): take value at address of x and then increment later. (x is still 1)
(++x): first increment value at address of x then take its value. (x becomes 2)
finally x++/++x i.e (2/2. This is because in second instruction value has become 2).
so it is 1. now final execution of 1st instruction (i.e increment value of x) is still left. so x becomes 1+1 i.e 2.
For simplicity Look this instruction set conversion:
Div &x,&(x++),&(++x)
++x will cause value to change 2.
so x becomes 2.
x++ will first use this 2 and then increment x by 1.
so 2/2=1 and increment it. =2
Hope tht helps :)
-1 for wrong answer. Its undefined behavior.
See here: stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points
Explanation:
x="++x/x++"=1
++x means the value of x at this instant is 2,again x++ means the value of x will be 3 only wen x comes again in the code.But see clearly,there is x=++x/x++;means,the value of x =2/2...Here x++ is not 3 as x/x is stored in x itself which comes to be 1............Great Question!!! :D
the answer is definitely 2.
Because in x = ++x/x++;
at a time the initial value stored in x will be fetched up by the expression.
so when ++x will put 2 for calculation, x++ will put 1 and result of div = 2.
By the time, ++x as well as x++ both might have written/overwritten the value of x = 2.
So consider any way, the result has to be 2 only.
Please take time to read this:
- Anonymous July 08, 2012stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points