Why nested functions can be cool.

Have you ever tried to use nested functions? ANSI C doesn’t like them, and only Gnu C supports them. Why are they good, aren’t they as evil as goto statements and global variables? I don’t think so. Most people aren’t use to them because they generally don’t occur in newer languages, but in languages such as Pascal, Ada, and Modula-2, they reign. Why are they useful? For information hiding of course!

Let’s consider a version of the Factorial algorithm in which the actual recursive function fact(), has no parameters, and returns nothing, using global variables instead. But not “global” variables in the same sense as C – variables which are accessible from a non-recursive wrapper function, factorial(). The wrapper function is called by the user and initiates the call to fact(), maintaining all the variables (n), and returning the result. The user has no access to fact(), as it is nested within factorial().

function factorial(x: integer): integer;
  var n: integer;
  function fact(): integer;
    if n = 0 then
      fact := 1
    else begin
      n := n - 1;
      fact := (n+1) * fact();

  n := x;
  factorial := fact();

It involves some modifications of the recursive function fact(), most noticeably the decrement of the variable n, prior to the recursive call. In earlier times, the replacement of parameters and local variables by “global” variables was a means of eliminating inefficient run-time stack manipulations of the variables and parameters.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.