Although i'm still a noob, there are many things I can understand with a bit of thinking, but this problem seems absurd. When writing a fibonacci generating function, if I pause the system after each generation it will generate the first number (3), and then generate the next one every time I press a button. BUT! If I simply cout the function one after another, it will end with the smallest, and start with the biggest... The only "rational" thought I could find (although irrational) was that the cpu generates the numbers before outputting them... Is it even possible?
// outputs: 3, 5, 8 etc..
#include "../std_lib_facilities.h"
int v1=1;
int v2=2;
int fib()
{
int s = v1+v2;
if (s<=0) s = 1;
v1 = v2;
v2 = s;
return s;
}
int main()
{
cout <<"1: "<<fib(); system ("PAUSE");
cout <<"2: "<<fib(); system ("PAUSE");
cout <<"3: "<<fib(); system ("PAUSE");
cout <<"4: "<<fib(); system ("PAUSE");
}
//And this option outputs: 13, 8, 5, 3...
#include "../std_lib_facilities.h"
int v1=1;
int v2=2;
int fib()
{
int s = v1+v2;
if (s<=0) s = 1;
v1 = v2;
v2 = s;
return s;
}
int main()
{
cout <<"1: "<<fib()<<"\n2: "<<fib()<<"\n3: "<<fib()<<"\n4: "<<fib()<<"\n";
}
The multiple function calls in the second program are executed from right to left, since they are all part of one cout statement. So, the last fib() gets a 3, the third (from left) one gets a 5, followed by 8, 13....
However, the printing is done from left to right and you would get something like
1 2 3 4
1. 13
2. 8
3. 5
4. 3
EDIT: I just learnt that C++ doesn't really guarantee in what order the function calls are executed but a lot of compilers do it from right to left.