Lil he*p with associativity and precedence here...

int x=4,y=9,z;
z=(++x)+(--x)+(x++)+(--y)+(y++)+(--y);
cout<<z;

Why is the output of this 35 ?
Please tell me... when I evaluate like this, i get 37. where am I going wrong :

z=5+4+4+8+8+8
=37
visual c++ gives this as 35
and bcc32 gives it 33
uhh come one
any one ???
it was 5 am here in the UK when you posted - we WERE all asleep.
Last edited on
oopsie !
I didn't know most of the people here were from UK ...
Very interesting. The C++ Standard says, ".. the order of evaluation of operands of individual operators ... and the order in which side effects take place is unspecified."

And gives the example:
 
      i = ++i + 1; // the behaviour is unspecified 


So, you're doing nothing wrong. C++ does not specify the order of all the ++, -- stuff and can do it in any order.

My G++ with no oprimisations gives: 35
My Visual Studio 2005 with no optimisations gives: 33

It's a trick question, but there's a lession in there somewhere.
Actually, the behavior for kbw's example is defined. It's the same as
1
2
i++;
i=i+1;

What the standard means to say is this:
When there is more than one side effect for the same variable in the same expression, the order in which these side effects will be executed is undefined.
Example:
a=a++ + a++ + a++;
VC++ will understand this as
1
2
3
4
a=a+a+a;
a++;
a++;
a++;
GCC will understand this as
1
2
3
4
5
6
a=a;
a++;
a+=a;
a++;
a+=a;
a++;


This can get pretty messy. In fact, I think right now I have a bug to eliminate because of this undefined behavior.
Ok,
I thought that there was something that only I didn't know about
Thanks you guys for replying..
Topic archived. No new replies allowed.