'C recursive function has extra output [closed]

This output:

4 4 7 4 11 4 7 4 4

Why is this the output from the following?

int f(int x)
{
    if (x == 0) return 1;
    else if (x == 1) return 3;
    else
    {
        printf("%d ", f(x - 2) + f(x - 1));
        return f(x - 1) + f(x - 2);
    }
}

void main()
{
    f(4);
}

I expected much less output:

4 7 ... 11


Solution 1:[1]

printf("%d ", f(x - 2) + f(x - 1));

is the same as

int a = f(x - 2);
int b = f(x - 1);
printf("%d ", a + b);

except it is not specified if a or b will be evaluated first.

In the recursion f(0) and f(1) doesn't print anything. f(2) prints 4 and in your case you just end up with f(2) being called twice before any other calls can print something.

You could try to figure out if your compiler evaluates a or b first from the output. Do that and you see why you get "4 4 ..."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Goswin von Brederlow