2

I am getting different answers for the same c++ code but in different versions of c++ i.e. c++14 and c++17

What are the changed made into c++17 from c++14 because of which I am getting different answers ?

(Specifically related to this question)

#include<iostream>

using namespace std;

int main()
{
    int i = 1;
    cout << i++ <<" "<< i-- << " " << i--;
    return 0;
}

/*
* Output in c++17
*   1 2 1
*
* Output in c++14
*  -1 0 1
*
*/

1 Answers1

1

C++17 changed the rules for the order of evaluation of some expression.

Let's rewrite the expression to its equivalent in function calls:

std::operator<<(std::operator<<(std::cout.operator<<(i++), " ").operator<<(i--), " ").operator<<(i--);

In C++14, the compiler was permitted to evaluate from right to left, or in ony nested order

To support chaining properly, C++17 states that such expressions are sequenced.

For example, std::operator<<(std::cout.operator<<(i++), " ").operator<<(i--) C++17 requires that i++ is evaluated before i--.

Guillaume Racicot
  • 32,627
  • 7
  • 60
  • 103