next up previous
Next: Variable-size arrays Up: intro_C Previous: Passing Arguments to main()


C has the interesting property that functions can be called recursively, that is, a function can call itself. Often this can make for elegant, but not necessarily efficient code. Recursive functions add to memory overhead and are not easily optimized when compiling. However, there are times when recursive calls are a natural choice, for example when handling tree-like data structures. Here's a simple example of a recursive function to compute the factorial of a number:

    long int factorial(int n)
        assert(n >= 0); /* negative values not allowed */
        if (n < 2) return 1; /* this is the exit condition */
        return n*factorial(n - 1);

This could equally well be written:

    long int factorial(int n)
        long int f;
        assert(n >= 0);
        for (f=n;n>1;n--)
            f *= (n - 1);
        return f;

Which version to use is mostly a matter of personal taste. Note that factorials get large very quickly, so even a modest value of n can result in a factorial that exceeds long int capacity.

Massimo Ricotti 2009-01-26