# What's going on

This is a discussion on What's going on within the C++ Programming forums, part of the General Programming Boards category; hi there, have a look at this; --- int x = 20; int y = 2; cout << --x + ...

1. ## What's going on

hi there,
have a look at this;

---
int x = 20;
int y = 2;

cout << --x + y << " " << x-=y++;
---
Why is the output : 20 18 !!!
It should, considering operator precedence be
21 17
am i missing somethimg?

2. I think the problem is with operator <<. try splitting it up into 2 lines then i bet you will get the expected result.

3. The only way I can see causing this is if 20 was sent to stdout before any evaluation. If it then got decremented to 19, then x = 19 – 3 (y++) = 16…. If the “+ y” from the earlier evaluation (it was not actually evaluated) is then added to the 16, we get the 18 that came to the screen.

Exactly how this is so…I don’t know…I am guessing. I thought the ‘+’ operator had a higher precedence than ‘<<’ So????

If anyone does get the proper answer, I would be very interested..

4. It's because the order that the expressions are evaulated is undefined. This thread went over some of the details.

5. its because operator << is right associative so it works out the last expression before the first one.

6. Oh right.... thanks for the pointer....I was wracking my brain over that

7. You could try putting the expressions in parantheses.

8. >>You could try putting the expressions in parantheses.

Nah..tried that.....first thing....

I understand now.... what is actually happening is

x-=y++ - First

--x + y - Second

Therefore,

x = 20 - 2 (y is incremented after.....I goofed this on earlier attempt )

x is now 18 (This is the final number to the screen)
y is now 3 (incremented after evaluation)

Then,

--x + y which is actually (18-1) + 3 = 20 (The 20 is the first number to the screen)

So the calculations go right to left, but the results are passed to cout left to right.......

Its amazing the knowledge you pick up spending an afternoon on the C++ board

Now the only mystery is who posted this to begin with