3

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;
    }
flora
  • 47
  • 5
  • you may speak about `recursive` functions. – Pierre Emmanuel Lallemant May 13 '18 at 16:42
  • 1
    `int fact(int n) { if(n == 1) return 1; return n * fact(n - 1); }` – Pierre Emmanuel Lallemant May 13 '18 at 16:44
  • and a `terminal` version of it would be `int fact(int n, int val) { if(n == 1) return val; return fact(n - 1, val * n); }` – Pierre Emmanuel Lallemant May 13 '18 at 16:45
  • are recursive functions by default reentrant ? is this what you mean ? – flora May 13 '18 at 16:45
  • https://stackoverflow.com/questions/261311/what-is-the-difference-between-re-entrant-function-and-recursive-function-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa with your example i'm not sure you are speaking of this. re-entrant = function possible to call from several threads, vs, recursive = function which calls itself in it's implementation. Are you sure your exercise is about "re-entrant" ? – Pierre Emmanuel Lallemant May 13 '18 at 16:49
  • Yes I am sure, "Write a reentrant Factorial function and a main program to calculate the factorial value of a given positive integer number." this was a question in an embedded C programming book – flora May 13 '18 at 16:54

2 Answers2

2

Your function, fact(n), neither used global or static data, did not modify its own code, and didn't call another non-reentrant function within.

Your function

int fact(int n){
   int c,fact = 1;
   for (c = 1; c <= n; c++)
       fact = fact * c;
    return fact;
}

was only called once in main.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
2

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.
Acorn
  • 24,970
  • 5
  • 40
  • 69