Interview Question
Country: United States
The output is undefined. There is no sequence point defined between the two expressions ++i & i++. Even if the expression is written like i=i++, the output is said to be undefined. A sequence point is also needed betwwen the two expressions i & i++, as the evaluation order of the expression is uncertain & varies from compiler to compiler based on parsing algorithm it follows to parse the instructions to be executed.
In simple words, if the value of the same variable is changed more than once in a statement, then it is said to be UNDEFINED BEHAVIOUR(UB).
A semi-colon is a sequence point where as +(plus) is not.
answer output would be 1 as i=++i/i++ the increment operator both post and pre happens only after the statement is executed, but in this particular statement both are equal to 5 and hence 1
check it for i=0 . Ans is 1 . Why ?
There's an increment because for i=-1 . Its showing an error . That means division by zero
now I understood, let us first take i=5;
now i=++i/i++;
calculation takes place from left to right OK
++i is executed (this is statement) ok
i=6
now i++ is executed
i=6 after statement is comeplete i becomes 7 but when calculaation is taking place it is 6/6 = 1
now is assigned 1
case i=-1
i=++i/i++
++i makes i=0
now i++ is executed bu when division is taking place i is still 0 and will become one when division is complete ( but before that division by zero)
case i=0
++i makes i=1
++i/i++ make 1/1 and then i should be incremented
so result is one
It contains side-effects. Hence the answer depends on the order of evaluation. Hence Compiler Dependent
- Luv July 03, 2012