...

/

Evaluation Order in C++17

Evaluation Order in C++17

Now let's try and understand evaluation order in C++ 17!

The example case

Press + to interact
#include <iostream>
class Query
{
public:
Query& addInt(int i)
{
std::cout << "addInt: " << i << '\n';
return *this;
}
Query& addFloat(float f)
{
std::cout << "addFloat: " << f << '\n';
return *this;
}
};
float computeFloat()
{
std::cout << "computing float... \n";
return 10.1f;
}
float computeInt()
{
std::cout << "computing int... \n";
return 8;
}
int main()
{
Query q;
q.addFloat(computeFloat()).addInt(computeInt());
}

You probably expect that using C++14 computeInt() happens after addFloat. Unfortunately, that might not be the case. For instance here’s an output from GCC 4.7.3:

computing int...
computing float...
addFloat: 10.1
addInt: 8

The chaining of functions is already specified to work from left to right (thus addInt() happens after addFloat()), but the order of evaluation of the inner expressions can differ. To be precise:

The expressions are indeterminately sequenced with respect to each other.

With C++17, ...