Dubious code using pre-increment operator in C++

Dubious code using pre-increment operator in C++

int n=3 ; n=++n + ++n; outputs n=10

But how ? In my pov it is like this,

-You first set ’n’ equal to 3.

  • You pre-increment it (increment it BEFORE you use it) - so now it’s 4.
  • Then you pre-increment it again - so now it’s 5.
  • Then you set n to n+n and since n is now 5 you get 5+5 which equals 10.

c++.png

n = ++n + ++n; //with n = 3

n = n + ++n; //with n = 4

n = n + n; //with n = 5

n = 10;

So it seems that the increment statements are processed first due to operator precedence, and the increment statement is “replaced by the variable itself”. But it's different in every language. As in JAVA the output is 9. This isn’t “illegal” - so you don’t get an error message and neither gcc nor g++ nor VisualStudio issues a warning message of any kind by default.

Compilers are not required to warn you when you do undefined things - and evidently, in this case, they do not do so. In the real world the last word is coming from the compiler (the compiler is always right).

It is just a matter of procedural semantics which is often given for granted by practical developers. So, knowing theory at this point might be extremely useful, as you might know in advance whether an expression might be interpreted differently from different compilers, as it is just a matter of definitions after all. The only thing you can do in practice is

1) in an exam, always state the assumptions such as the expression evaluation order, and the semantics associated to the increment.

2) In real life, use the less ambiguous syntax as possible, thus ensuring that all the compilers will evaluate the expression in the same way (e.g., this can be achieved by first performing the increments, getting the values before/after the increments, and then performing the sum). Similar cases can happen with operators’ priority (evaluation order): try to use parentheses as much as possible to force evaluation in a given interpretation and evaluation order.