0

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!

user4581301
  • 33,082
  • 7
  • 33
  • 54
Cantafford
  • 31
  • 1
  • 7
  • Also the function prints nothing, it returns a value. And it’s not that the order changes runtime. It’s just not specified so the compiler can make it either way. It still will be consistent runtime, you just can’t trust which way it is on different compilers etc. – Sami Kuhmonen Dec 02 '17 at 06:38
  • 1
    " First time you call get_num a static i variable is created then is incremented by 1 and then is printed". This is not what is happening. Two numbers are generated, then both are printed. – Rotem Dec 02 '17 at 06:45
  • 1
    *To make things even less clear to me when I try to compile this code I always get '2,1'* -- If you were to change compiler, compiler options, or even switch to another version of the same compiler, you may see different results. Unlike most other computer languages, in C++ there are things that are *unspecified behavior* and *undefined behavior*. Parameter order processing is one of those unspecified things. – PaulMcKenzie Dec 02 '17 at 06:48
  • You're assuming the arguments are evaluated left-to-right. There is no evidence to allow you to make this assumption. – Silvio Mayolo Dec 02 '17 at 06:50

0 Answers0