Search code examples
crecursionfactorial

factorial of a given number using recursion without return statement in recursive function is returning the correct answer


`

#include <stdio.h>

int k = 0;

int factorial (int x)
{
    if (x == 1)
    {
        return 1;
    }
    
    k = x * factorial (x - 1);
}

int main()
{
    printf ("Factorial of %d is: %d\r\n", 5, factorial(5));

    return 0;
}

Factorial of 5 is: 120

I have been learning recursion for the last few days, and while working on the factorial of a given number using recursion, everything works fine, but the question I am having is that the above code, without any return statement, is printing the value 120 in the console for the factorial of 5.

Also, I am curious to know how, without any return statement except in the base condition of the factorial function, the recursive call is giving the correct answer.

if (x == 1)
{
return 1;
}
k = x * factorial (x - 1);

As per my understanding, the above line of code would execute like this:

k = 5 * factorial (5-1)
k = 4 * factorial (4-1)
k = 3 * factorial (3-1)
k = 2 * factorial (2-1)
k = 1 * factorial (1-1)
return 1; --> when x is 1

What value it will have in the factorial (x - 1) is something I don't understand. Because this factorial (x) function does not have any return statements.


Solution

  • If a function is defined to return a value but doesn't, and if an attempt is made to use the return value, this triggers undefined behavior in your program.

    One of the ways undefined behavior can manifest itself is that the program appears to work properly. There is however no guarantee of this result, and in fact making seemingly unrelated changes to your code can change how undefined behavior can manifest itself.