increment operator

if a=0
b=(++a) + (++a)
then b is coming out to be 4.
can any1 explain me how??
Because you are invoking undefined behavior. It could just as easily be 100 or -22.
closed account (z05DSL3A)
In this case it would seem that

a = 0
b = (++a) + (++a)
b = a + (++a) and a =1
b = a + a and a =2
b = 2 + 2
b = 4

As the standard dose not specify the order of evaluation it could as easily been

a = 0
b = (++a) + (++a)
b = a + (++a) and a =1
b = 1 + (++a)
b = 1 + a and a =2
b = 1 + 2
b = 3

Grey Wolf wrote:
As the standard dose not specify the order of evaluation it could as easily been

a = 0
b = (++a) + (++a)
b = a + (++a) and a =1
b = 1 + (++a)
b = 1 + a and a =2
b = 1 + 2
b = 3


I donĀ“t totally agree with this , because the parenthesis have a higher precedence so the ++a should be evaluated first...

without the parenthesis it is undefined , in my opinion...
Last edited on
It doesn't matter. The order of evaluation of increments and decrements is undefined. It doesn't depend on parentheses.
If there was a comma around there, however...

http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15
The parenthesis are meaningless here because the ++ operator has a higher precedence than the + or = operators anyway.

So it's undefined in either case.

The compiler is free to choose to do it like so:

1
2
3
4
5
6
b = (a+1) + (a+1);
a += 2;

// end result:
//  b == 2
//  a == 2 


or it could do it as either way Grey Wolf suggested. Or it could do it some other completely different way we haven't speculated yet.

Bottom line: you cannot modify a variable more than once between sequence points. The sequence point here is the semicolon. Since we're modifying a twice before the semicolon, the result is undefined.
Last edited on
Topic archived. No new replies allowed.