Search code examples
crecursionfactorial

Factorial program with STATIC INT


how this program behaves,

fact(static int n)
{
  int f=1;
  if(n<=1) return 1;
  else
  {
   f=n*fact(n-1);
   return f;
  }
}

how the function calls and return values depends on n and why final output is 1.


Solution

  • Some embedded C compilers support static as a parameter specifier as a non-standard extension. For these compilers, static means a parameter that is globally allocated (generally, this is done to save stack space, which can be very limited on an embedded platform).

    In this case, the presence of a static parameter means the function is not re-entrant (cannot recurse safely). A globally allocated n would simply change on every call until the final call fact(1); as the recursion unwinds, every returning call will multiply n (now equal to 1) into the result, so the net effect is that a bunch of 1s are multiplied together to produce the final result.