2

Lets say I have the following code

#include <iostream>


int main() {
    int i = 3;
    std::cout << ++i << " " << i++;
}

Since the first increment is done before, and the second one after, I expected that code to output this:

4 4

And if not, I would have expected it to at least output this:

5 5

But instead what I get is:

5 3

which makes no sense what so ever. What is going on? I compiled it with g++ -std=c++14 test.cpp -o test

segj
  • 101
  • 1
  • 8
  • Does this answer your question? [i = ++i + ++i; in C++](https://stackoverflow.com/questions/340282/i-i-i-in-c) – Lukas-T Jan 22 '20 at 07:40
  • Does this answer your question? [Order of evaluation of arguments using std::cout](https://stackoverflow.com/questions/7718508/order-of-evaluation-of-arguments-using-stdcout) – Matthias Jan 22 '20 at 07:47
  • All the linked dupes are good. So, in the end you should get 4, 4 when compiling with -std=c++17 and undefined behaviour with earlier standards. – Lukas-T Jan 22 '20 at 07:51
  • Thank you, the linked pages answered the question, I just couldn't find them earlier. So it is undefined behaviour as I suspected. My compiler doesn't seem to support c++17 so I cannot test if the behaviour is different in that standard. – segj Jan 22 '20 at 15:18

0 Answers0