Problem with understanding Operators

Started by
16 comments, last by TDragon 18 years, 6 months ago
My C++ instructor has recently been explaining the unary prefix and postfix operators (mainly ++ and --) It shows out that: ++a + ++a is equivalent to (++a, ++a, a + a) so if a = 1 it returns 6 I tried it on Borland and VC++6.0 and it worked as he said However I thought it would return 5, as in it adds one to a, (a=2), it adds one to the next a (a=3) so the expression will be 5 ++a + ++a ++1 + ++a 2 + ++a 2 + ++2 2 + 3 5 Am desperate, and I know it has to do with precedence
[ my blog ]
Advertisement
The statement ++a + ++a is undefined, as it involves mutation of a value twice between sequence points.

The compiler is free to spit out whatever it feels like, really.
ouch.
Quote:Original post by arithma
Am desperate, and I know it has to do with precedence

Speaking strictly from an operator precedence point of view, pre-increment has higher precedence than addition, so both increments will be done before the addition. Where things get really weird is with post-increment: what are the values of a and b after the following statements?
int b, a = 1;b = a++ + a++;


This is why some languages don't have increment operators, like Python.
The replies are still inconclusive: who is right
Does ++a + ++a have a defined behavior indorsed by the standard, or is it left to the compiler to decide upon it
[ my blog ]
Quote:Original post by arithma
The replies are still inconclusive: who is right


What do you mean? Only one person has posted about this.
Ooops,
I didn't see that the same person was posting as I rushed into viewing the reply

However, can I conclude that the standard doesnot impose the order-of-precedence point-of-view?
[ my blog ]
Quote:Original post by arithma
Ooops,
I didn't see that the same person was posting as I rushed into viewing the reply

However, can I conclude that the standard doesnot impose the order-of-precedence point-of-view?


Since the + operator is not a sequence point, the operands could be evaluated in any order.
Quote:Original post by arithma
However, can I conclude that the standard doesnot impose the order-of-precedence point-of-view?

It has nothing to do with order of operations. As Oluseyi has stated, multiple modifications of a single variable in between sequence points is undefined. It's not supported by the standard, and is compiler-implementation defined.

Read more about it here.
:stylin: "Make games, not war.""...if you're doing this to learn then just study a modern C++ compiler's implementation." -snk_kid
Undefined Behaviour. The compiler really can do whatever the hell it likes with that code!
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement