Fibbonnaci generating

Hi everybody,

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

// 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";
}


Thanks!
Last edited on
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.
Last edited on
Interesting...
Thank you very much!
It is not absurd and it has nothing to do with "PAUSE". Change line 48 to
1
2
3
4
    cout <<"1: "<<fib();
    cout <<"\n2: "<<fib();
    cout <<"\n3: "<<fib();
    cout <<"\n4: "<<fib();


It has to do with order of evaluation:

http://en.cppreference.com/w/cpp/language/eval_order

It is not defined (on line 48) when the functions are called and the result is used.

While when you write it like in the first main() the order is defined.
Topic archived. No new replies allowed.