# Postfix operation

Vidyavathi saravanan
Ranch Hand
Posts: 34

This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.

Chris Allen
Ranch Hand
Posts: 127
Originally posted by Vidyavathi saravanan:

This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.

The way I got to the answer was as follows:
int a=1;a += ++a + a++;
then: a += (2) + a++;
then: a += (2) + (2); ->a will be incremented to 3 once the statement is finished
then: 1 += (2) + (2);
equals: a=5 (assign 5 to the value of a)

Remember that the postfix operator only takes effect AFTER the statement is processed and as such, is not involved in the calculation of this line. Since the value of a has already been set to 5, the effect is that the value of a is incrmented but it is not assigned to a and basically is lost.

Think of it this way:
We have already assigned the value of the variable a so you can increment it, but it will be ignored as the assignment is already done.

Ilja Preuss
author
Sheriff
Posts: 14112
What actually happens is the following:

a += ++a + a++; (a==1)
a = a + ++a + a++; (a==1)
a = 1 + ++a + a++; (a==1)
a = 1 + a + a++; (a==2)
a = 1 + 2 + a++; (a==2)
a = 3 + a++; (a==2)
a = 3 + 2 [need to increment a now]; (a==2)
a = 3 + 2; (a==3)
a = 5; (a==3)
(a==5)

That is, a does get incremented, but before the assignment of the expressions value happens.

Does that help?