0

I recently started studying c++. Can you please explain me the output of the following program, it is not clear for me how it works. I know that at ++a at first 1 is added and then a is used, where as at a++ is the other way around. However the next output is confusing.

int main()
{
    int a = 0;
    cout << a << " " << a++ << " " << ++a << " " << a << "\n"; // 2 1 2 2
    //cout << a << " " << ++a << " " << a++ << "\n"; // 2 2 0
    //cout << a++ << " " << a << "\n";  // 0 1
}

Output 2 1 2 2

Sandu
  • 1
  • 2
  • 3
    Update your compiler and/or enable C++17. This was UB pre-C++17 (as the link shows), and since C++17 it has to print `0 0 2 2`. – HolyBlackCat Oct 04 '21 at 11:31
  • 2
    Even if you use C++17 or later, avoid this kind of code that does multiple mutations of the same variable in the same statement. Bad code smell. – Eljay Oct 04 '21 at 11:53

0 Answers0