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?
printfwith variable number of parameters, where evaluating right to left is good, because it leaves the format string on top. The compiler can choose any order it likes, and if you prefer a specific order, use version 2.