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?
please help!
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?
please help!
I think the problem is with operator <<. try splitting it up into 2 lines then i bet you will get the expected result.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
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..
It's because the order that the expressions are evaulated is undefined. This thread went over some of the details.
zen
its because operator << is right associative so it works out the last expression before the first one.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Oh right.... thanks for the pointer....I was wracking my brain over that
You could try putting the expressions in parantheses.
>>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