Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my factorial function reentrant?

I am supposed to write a reentrant factorial function, when I searched what a reentrant function is, I found many definitions, such as a reentrant function shouldn't use static or global variable,and the function cannot be changed while in use , I avoided using static or global variables, but I don't know if it is enough for my function be be reentrant or not,

    #include <stdio.h>

    int fact(int n){
       int c,fact = 1;
       for (c = 1; c <= n; c++)
           fact = fact * c;
        return fact;
    }
    int main()
    {   
        int n;  
        printf("Enter a number to calculate its factorial\n");
        scanf("%d", &n);
        fact(n);
        printf("Factorial of %d = %d\n", n, fact(n));

      return 0;
    }
like image 500
flora Avatar asked Jan 29 '26 09:01

flora


1 Answers

As written, your function is not just reentrant, it is also pure (in the terminology of some compilers, __attribute__((const))).

The reason is that:

  • It has only the side-effect of returning a value.
  • Its return value depends exclusively on the value of the parameters.
like image 118
Acorn Avatar answered Jan 30 '26 22:01

Acorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!