Printing problem

Different compilers are giving different answer for this print statement. One is evaluating the eq from left while other from right. One gives 343 the other 332. What should be the correct answer. If we start from right to left its 332 but from left to right its 343

1
2
  int a=3;
cout<<a<<++a<<--a;
you found that correct answer already: it's compiler dependent.

just avoid changing a variable while it's evaluated
One is evaluating the eq from left while other from right.

That's only an unsubstantiated guess.

What should be the correct answer

There is no correct answer. The expression is undefined because it attempts to modify a scalar twice, and also because it attempts to read and modify it on the same sequence point.

for laughs, here's what the compilers I use printed:
sun/solaris: 333
xlc/aix: 343
gcc/linux: 333
gcc/aix: 343
clang/linux: 343
Last edited on
The standard in ยง5/4 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.

By doing that, you're invoking undefined behavior; there's no such thing as a "correct answer."
Topic archived. No new replies allowed.