Today i came across a code which i am not able to understand.It would be great if someone could explain the output and behaviour of the code.
i=1;
ans=i++ + ++i;
Now output of this code is 4.
I understand that increment operators have right to left associativity.
Now consider this code
i=1;
ans=i++ * ++i;
output of this code is 3.
How? Why does it behave differently in these situations.Can someone please elaborate and explain how to both of the expressions evaluate???
Wait, I couln’t identify the problem.
i++ --> 1; i is now 2
++i --> 3; i is now 3
ans = 1 * 3 = 3
Let’s analyse the case 1
first i=1
ans=i++ (after this ans=1,i=2) as i++ first takes the current value of i for the current operation
and then increment it
ans=i++ + ++i(when you do ++i i becomes 3 from 2) as ++i first increment i and then take the incremented value of i for operation so
ans=1+3, this gives ans=4
Now for 2nd case
i=1
ans=i++ (ans=1,i=2) same as before
ans=i++ * ++i (i was 2 now becomes 3) same as before
so ans=1*3, this gives ans=3
It is often advised not to use ++/-- with same variable more than once in a single statement. Doing so results in compiler dependent behaviour. Which cannot be predicted using a pen and paper. Try running same commands on different compiler of c/c++. You will be definately surprised by the result.
Reason for this is due to undefined behaviour of +,-,*,/ sign. There is no hard and fast rule for these operators as to which side(left operator or right operator) should be executed first. As a result different compilers use different approaches for calculating answer.
A logic can be created to convince ourself with the answer but this cannot help us guarantee/ predict the result next time.
My advice, which I give to everyone who ask me these type of questions, here is Just avoid brainstorming with these type questions. Because there is lot more to learn.
okay i understand now, i read in C by dennis Rithcie that associativity of ++ is from right to left so i thought it would increment from right to left, so i was confused