Search code examples
crecursionparametersfactorial

Factorial recursion with a pass by reference function call?


I want to create a recursive Factorial using the Pass By Reference method.

int recursiveFactorialByValue(int x){

if (x==0||x==1) return 1;
else if (x<=0) return -1;
else return x * recursiveFactorialByValue(x-1);
}

void recursiveFactorialByReference(int *x){

int minusOne = *x - 1;
int *ptr = &minusOne;
if (*x==0||*x==1) *x = 1;
else if (*x <= 0) *x = -1;
else *x * recursiveFactorialByReference(ptr); //this is where the error occurs
}



int main(){

int x, *ptr=&x, **pptr=&ptr, y;

printf("Enter a positive integer: ");
scanf("%d",*&x);
y = x;

printf("%i! = %i\n",y,recursiveFactorialByValue(x));


recursiveFactorialByReference(ptr);
printf("%i! = %i\n", y, x);
return 0;
}

I get this error:

In function 'recursiveFactorialByReference':
14:7: error: void value not ignored as it ought to be
else recursiveFactorialByReference(ptr) * *x;

I've tried different function calls like:

else *x = *x * recursiveFactorialByReference(*x-1);

else *x = *x * recursiveFactorialByReference(ptr);

and none of these work, I can't find the problem please help.


Solution

  • *x * recursiveFactorialByReference(ptr)
    

    This multiplies the value pointed to by x (which is an int) with the return value of recursiveFactorialByReference (which is void), which makes no sense. Think about what your recursive function does: you pass it a pointer to an int and it replaces that int with its factorial. So your recursive part should look like this:

    else
    {
        recursiveFactorialByReference(ptr);
        *x *= *ptr;
    }
    

    Note that you still have to assign to *x. Multiplying it on its own just throws away the value.

    Also you have an extra * in your scanf call. It should be

    scanf("%d", &x);
    

    Also these technically aren't "references" (that's a concept from C++). Both of your functions are passing values, the latter just happens to be passing the values of pointers.