Evaluation order of function arguments
suggest changeIf a function has multiple arguments, which argument is evaluated first is unspecified. Since C++17 the evaluations are indeterminately sequenced: one argument, including initialization of its parameter, finishes before the next starts. Before C++17 the evaluations were unsequenced, but function calls never interleave, so get_val modifying its static in both calls is not undefined behavior. The following code can print x = 1, y = 2 or x = 2, y = 1.
void f(int x, int y) {
printf("x = %d, y = %d\n", x, y);
}
int get_val() {
static int x = 0;
return ++x;
}
int main() {
f(get_val(), get_val());
}
In C++17, the order of evaluation of function arguments remains unspecified.
The postfix expression that selects the function is sequenced before any argument. Each argument, including construction of the parameter, is completely evaluated before another argument starts.
struct from_int {
from_int(int x) { std::cout << "from_int (" << x << ")\n"; }
};
int make_int(int x){ std::cout << "make_int (" << x << ")\n"; return x; }
void foo(from_int a, from_int b) {
}
void bar(from_int a, from_int b) {
}
auto which_func(bool b){
std::cout << (b ? "foo" : "bar") << "\n";
return b?foo:bar;
}
int main(int argc, char const*const* argv) {
which_func(false)( make_int(1), make_int(2) );
}
This prints one of the following:
bar
make_int (1)
from_int (1)
make_int (2)
from_int (2)
or
bar
make_int (2)
from_int (2)
make_int (1)
from_int (1)
It may not print bar after any of the make_int or from_int lines, and it may not print:
bar
make_int (2)
make_int (1)
from_int (2)
from_int (1)
or a similar interleaving. Prior to C++17, printing bar after the make_int calls was legal, as was evaluating both make_int calls before either from_int constructor.