Ricky
Ricky

Reputation: 705

Function returning value with no specified return statement in the control flow structure

Today I was experimenting with random C code and I found something that confused me. In the following program:

#include <stdio.h>
int f(int x)
{
        if(x==2)
        return 2;
        else
        {
                printf("+");
                f(x-1);
        }
}
int main()
{
        int n,i;
        n = f(6);
        printf("%d\n",n);
}

The output is quite expectedly ++++2, there is no confusion about the number of '+' because the number of recursive calls is 4. But my question is about the return value 2. In the function, a value is returned when the if(x==2) condition holds. Now when the function is being called with numbers other than 2, it will enter the else block. There is no explicit return statement in that block. But still it is returning a value. How is it allowed? How is the program deciding to return a number even when it is not explicitly told to do so? Is it that the program is simply returning the number it obtained from the recent function call? When a function is called, the caller maintains a stack. The return value is stored in a register. Is the function supposed to return the value stored in that register? Someone please explain it.

Upvotes: 0

Views: 57

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

In case the } that terminates the function is reached, and the returned value is used in the caller, the behavior of the program is undefined. You cannot expected any reasoning for the value you got as return. In another run, it may return a completely different integer value, return the complete lyrics of your favorite song, or set your computer on fire. Nothing is guaranteed.

Quoting C11, chapter §6.9.1

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

Upvotes: 1

Related Questions