# Problem with understanding Operators

This topic is 4702 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
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.

##### Share on other sites
Quote:
 Original post by arithmaAm 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.

##### Share on other sites
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

##### Share on other sites
Quote:
 Original post by arithmaThe replies are still inconclusive: who is right

##### Share on other sites
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?

##### Share on other sites
Quote:
 Original post by arithmaOoops,I didn't see that the same person was posting as I rushed into viewing the replyHowever, 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.

##### Share on other sites
Quote:
 Original post by arithmaHowever, 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.

##### Share on other sites
Undefined Behaviour. The compiler really can do whatever the hell it likes with that code!

1. 1
2. 2
JoeJ
20
3. 3
frob
19
4. 4
5. 5

• 10
• 10
• 12
• 13
• 9
• ### Forum Statistics

• Total Topics
632199
• Total Posts
3004736

×