I am reading the book of CPP-Concurrency-In-Action-2ed-2019. In chapter 5.3.2, the author gives a simple example:
#include <iostream>
void foo(int a, int b)
{
std::cout << a << ", " << b << std::endl;
}
int get_num()
{
static int i = 0;
return ++i;
}
int main()
{
foo(get_num(), get_num());
}
It says the two times of calling get_num() are in random sequence. And it could output 1, 2 or 2, 1.
But is it the same with below, which is definitely output in a fixed sequence.
int main()
{
auto a = get_num();
auto b = get_num();
foo(a, b);
}
So why does the former output randomly?
It boils down to: "These are the rules"
The C++ standard committee decided that they don't want to specify an order. This leaves it up to the compiler to decide which argument to evaluate first. The compiler may decide that the code would be more efficient if
bis evaluated beforeaor the other way around. If the committee would have decided that the arguments need to be evaluated in order, compilers might have to generate less efficient code in certain situations.