I'm following a C++ pdf book and I got to this code snippet example:
#include <iostream>
using namespace std;
void foo(int a,int b)
{
cout << a << ", " << b << endl;
}
int get_num()
{
static int i=0;
return ++i;
}
int main()
{
foo(get_num(),get_num());
}
Now in the book the author says: "You know that the program in the following listing will output “1,2” or “2,1”, but it’s unspecified which, because the order of the two calls to get_num()is unspecified."
I'm no expert in C++ so that makes no sense to me. The way I see it: First time you call get_num a static i variable is created then is incremented by 1 and then is printed so first time function should print 1. Second time when you call get_num the i is incremented and then printed out so it should print 2.
So when I do: foo(get_num(),get_num());
the first parameter(a) which is printed first by the 'foo' function should recieve the value of the first call to get_num which is '1' and then the second parameter(b) should recieve the value of the second call to get_num which is '2'.
So the way I see it I should always be recieving 1,2 in this order. Now the book says that the order to the two get_num's is unspecified so you could get 1, 2 or 2, 1 printed as result. To make things even less clear to me when I try to compile this code I always get '2,1'. :)
Please help me understand what's going on there(meaning what values should I see and in which order and why). Thank you for reading!