Search code examples
cfunctionrecursionreturnfactorial

Unable to return correct value of a variable in a recursive function


I am making following program to find factorial of a given number recursively.

#include<stdio.h>
int fact1=1;

int recursion(int x)
{
    if(x==0)
    {
        return fact1;
    }

    fact1=fact1*x;
    x--;
    recursion(x);   
}

int main()
{
    printf("%d",recursion(5));
    return (0); 
}

Problem :

The problem is that whenever I run this program it always gives me some garbage value 22752240 .

Thus Inorder to test my recursion I placed printf("%d",fact1) in the recursive function to check whether fact1 was 120 before being returned

int recursion(int x)
{
    if(x==0)
    {
        printf("%d",fact1);
        return fact1;
    }

    fact1=fact1*x;
    x--;
    recursion(x);   
}

and when I executed program I got this 120 22752240 as output, meaning that recursion() was printing correct value of fact1 but was unable to return correct value of fact1.

Can anyone explain why is this happening?


Solution

  • Sure. you forgot to return a value at the very the end of recursion(). Without that return statement, the use of recursion() as an argument ot printf() invokes undefined behaviour.

    To elaborate, only for the case when x == 0 is TRUE, you're using a return statement to return a value. In other scenario, you're missing a return statement. You need to add return statement for other case also.

    Reference: Form C11 standard, chapter §6.9.1, Function definitions

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

    That said, the recommended signature of main() is int main(void).