Returning from a Deep Recursion

Let us apply the idea discussed so far to write a factorial computation program. Click here to download a copy of this program.

#include  <stdio.h>
#include  <setjmp.h>

jmp_buf   JumpBuffer;

int       result;

void  main(int argc, char *argv[])
{
     int  n;

     n = (int) atoi(argv[1]);
     if (setjmp(JumpBuffer) == 0) 
          factorial(n);
     else
          printf("fact(%d) = %d\n", n, result);
     exit(0);
}

void  factorial(int n)
{
     fact(1, 1, n);
}

void  fact(int Result, int Count, int n)
{
     if (Count <= n)
          fact(Result*Count, Count+1, n);
     else {
          result = Result;
          longjmp(JumpBuffer, 1);
     }
}