-1
int a = 3;
cout << ++a << a++ << ++a << a++ << endl;

The answer of this code snippet is 7573 on codeblocks::mingw. What i got till now is that post increment goes in the right way but the preincrement has some different logic. The last value of last preincrement will be same for all preincrements. Can anyone tell me what actually happens there with ++a.

And one more thing the code needs to be solved from Right to left. Thanks for any answer.

M.M
  • 138,810
  • 21
  • 208
  • 365
Kya Pata
  • 9
  • 2
  • 1
    This is not C... – dbush Jul 20 '18 at 03:43
  • 1
    While the dupe link is about C, I'm fairly sure it's the same in C++ (before C++17, I'm unsure afterwards). – iBug Jul 20 '18 at 03:43
  • "the code needs to be solved from Right to left." - huh? – M.M Jul 20 '18 at 03:48
  • reopened - the suggested duplicate was a different language question that is mostly not applicable here – M.M Jul 20 '18 at 03:59
  • M.M's answer is good. But I think you haven't learnt that much. If you are a beginner, avoid this usage. I mean, your code is involved in 2 questions: 1. difference between `i++` and `++i`, 2. *order of evaluation*. – Rick Jul 20 '18 at 04:39

1 Answers1

6

Since C++17::

In a shift operator expression E1<<E2 and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2

So the output is well-defined and should be 4466.

Prior to C++17 the code caused undefined behaviour as explained here. Your output suggests that you are using an old compiler (or invoking the compiler in old mode).

M.M
  • 138,810
  • 21
  • 208
  • 365