Unexpected value of the expression

This may be a trival question and i’m not able to understand the reason. Any input can be of great help. I used g++ to compile.


x=5;
y = ++x * ++x;
cout << y << endl;

To my suprise, the value outputed for the above code is 49 and not 42 (6 * 7).

Also when

y = ++x * ++x * ++x;

, the output is 392 (maybe = 7 * 7 * 8). So, we cannot say that precedence of ++ is more than * operator.

Precedence of ++ operator is more than * operator. So first both ++ operators are evaluated which gives x value equal to 7 then * operator is evaluated which gives 49.

Source

The expression is ill-defined wrt. the C-Standard. he only rule you have is that x is incremented before being evaluated and both arguments of the multiplication are evaluated before being multiplied. calling the incrementations inc1 and inc2, the evaluations ev1 and ev2 and the multiplication mult, you have inc1<ev1, inc2<ev2 and ev1<mult, ev2<mult where < is the order of computation. So you could have for example

inc1<ev1<inc2<ev2<mult or inc1<inc2<ev1<ev2<mult or inc2<ev2<inc1<ev1<mult

yielding different results. Different compilers on different architectures might use the same ordering, but a compiler might use a different ordering when it is more efficient.

Similarly for the cubic expressions the compiler seems to choose (notations analogous as above)

inc1<inc2<ev1<ev2<mult1<inc3<ev3<mult2

or something similar, but other orders would be permissable too.

So in general don’t use such a construct

If the reasoning was correct the result of y = ++x * ++x * ++x; should be 8^3, but it isn’t

first both ++ operators are evaluated which gives x value equal to 7 then * operator is evaluated which gives 49.