Search⌘ K
AI Features

Evaluation Order in C++17

Explore the changes in evaluation order introduced in C++17 that ensure inner expressions and operator overloads are executed from left to right. Understand how this impacts function chaining and operator overloading behavior, improving code clarity and predictability.

The example case

C++ 17
#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, ...