reason for the output?

int main()
{
int a=2;
cout<<++a + ++a;
system("pause");
}

The output that I expected was 7 but the output was 8. could I know the reason for it...
Last edited on
I'm pretty sure performing multiple manipulations of a variable like that (EDIT: in one line, iirc) is language-illegal, and therefore compiler-dependent and unpredictable. I recall seeing it in a link to parashift somewhere. But I can't verify this because I forget the link.
Last edited on
but it just occurs with two such manipulations done. If three or more are done the output just differs with the result of the two manipulations....

int main()
{
int a=2;
cout<<++a + ++a;
system("pause");
}

gives the output 8

int main()
{
int a=2;
cout<<++a + ++a ++a;
system("pause");
}

gives the output 5+8 i.e 13.

and after two manipulations even if number of manipulations are added the output doesn't differ except for the dependency on the output ofthe two manipulations. can I know why?
Last edited on
closed account (z05DSL3A)
The order of evaluation of expressions is defined by the specific implementation, except when the language guarantees a particular order of evaluation (as outlined in Precedence and Order of Evaluation). Relying on the side effect of the incrementation to be carried out in any particular order is not recommended as it has no specific order of evaluation in the expression.

Edit:
1
2
3
4
5
6
int main()
{
int a=2;
cout<<++a + ++a ++a;
system("pause");
}


It would appear that to evaluate the above it is doing

(++a + ++a) and ++a.
it increments a twice to evaluate (++a + ++a) which leads to (4+4) and then increments a again to evaluate ++a.
So now it has (4+4)5, it send 5 to cout and evaluates (4+4) and sends that to cout. so cout shows 5+8.
Last edited on
Which is why excessive use of in-line incrementation/decrementation is not a good idea.
Topic archived. No new replies allowed.