-1

`

#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.

  • 3
    That's sad. Your undefined behaviour is producing the expected result (even though there are no good grounds for expecting that result). That's bad luck, as well as sad. But it's still undefined behaviour and you can't rely on it. To make the code reliable, you need an explicit `return k;` as the penultimate line of `factorial()`, before the close brace `}`. – Jonathan Leffler Jan 01 '23 at 05:31
  • 1
    Obviously undefined behaviour, but which compiler, version, platform and architecture? You could look at the disassembly and see how it works. For example, a hypothetical platform and compiler might use a calling convention that returns the result of `factorial` in a particular register - which then coincidentally that same register was also chosen as an intermediate to move the value into `k` (which would have been the result), and the register remained unmodified for the remainder of the function. The slightest change could break it. – Wyck Jan 01 '23 at 05:42

1 Answers1

2

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.

dbush
  • 205,898
  • 23
  • 218
  • 273