# unary postfix operators

Timothy Sheehy
Greenhorn
Posts: 3
Hi all,

I'm very confused by a simple section of code that is not giving expected results!

What should be printed out? I wuold say 5, but I am wrong.
I cannot figure out why!

A similar phenomenon happens with the postfix -- operator.

However:

This gives the expected result a = 7, b = 8

Can anyone shed any light on this?

Thanks!

Peter Chase
Ranch Hand
Posts: 1970
Originally posted by Timothy Sheehy:

What should be printed out? I wuold say 5, but I am wrong.
I cannot figure out why!

The line "s = s++" does the following:

• Get the value of the expression s++, which is 4
• Increment s to 5
• Assign the value of the expression to s, putting it back to 4

• If it was "s = ++s", it would make s equal 5, though it would be an odd (inefficient) way to do it.

Timothy Sheehy
Greenhorn
Posts: 3
Thanks Peter, I understand.

I read it as the entire line must be evaluated before the post-increment.
However, the expression of the right hand side of the = operator must be completely reduced before the asignment can be affected.

The RHS is evaluate. The ++ is executed. The RHS has been reduced (to 4) and can now be used in the assignment.

Thanks for the feedback. This has been troubling me for a couple of hours now.

Cheers!

Mahesh Bhatt
Ranch Hand
Posts: 88
hi

if your doubt is regarding the postfix and prefix operations . Try the following.
keep in mind the variable "x" , and the "expression" , then as you solve the expression step by step .... keep in mind the golden rule :

1) when its ++x , increment x and then assign the value of x in the expression .

2) when its x++, first assign the value to the expression and then increment the value of x.

ex : int x=0;
int y= x++ + ++x +++y + y++;

try solving this simple problem with keeping the golden rule on your "tounge" ...if u can solve this (please match the result you get with the result that the computer gives ) the ...u can solve any complex problem .
[ September 16, 2004: Message edited by: prashant bhogvan ]

Timothy Sheehy
Greenhorn
Posts: 3
That's a great trick.

Thanks!

Abhi Raj
Greenhorn
Posts: 7
The example as above will not compile as y has not been initialized. Need to do :

int x=0;
int y=0; //***initialize y first
y = x++ + ++x + ++y + y++;

I think it would make a good interview question