I do not understand why the output of following program is 63
:
#include <iostream>
int main() {
int a = 20;
a += a + ++a;
std::cout << a;
}
I was expecting it to be 61
. What exactly a += a + ++a;
does?
I do not understand why the output of following program is 63
:
#include <iostream>
int main() {
int a = 20;
a += a + ++a;
std::cout << a;
}
I was expecting it to be 61
. What exactly a += a + ++a;
does?
Standard says: "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression" (5 Expressions, §4), i.e. the following:
a += a + ++a
yields undefined behavior just like:
a = ++a;
does already. It also says: "the prior value shall be accessed only to determine the value to be stored", i.e. if you want to change a
, you can use a
in the same expression just to retrieve the previous value:
a = a + 1; // OK
... "otherwise the behavior is undefined."
You're triggering undefined behavior and there is no 'correct' answer. Your compiler can chose what order to evaluate the arguments of the plus operator.
it looks like ++a
is evaluating before the rest of the expression, so it's as though a
is 21` in a statement like
a += a + a;
at any rate, don't use ++a
inside of an arithmetic expression like that anyway. It's confusing for people, and is probably undefined behavior