This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Local Functions In C++
  Submitted by



Haven't you ever wanted to make a function that is logically defined inside the scope of another function? It would look like the following, which is NOT valid C++:

void MyFunction()
{
   void RecursiveFunction(int i)
   {
     if (i  0) RecursiveFunction(i-1);
   }

RecursiveFunction(6); }


If so, you've wanted to make what's called a local function. I remember using and loving them back in my Turbo Pascal days. When I started using C and C++, I missed them often. So I had to separate the functions in this manner, which looks uglier and does not use the logical scoping:

static void RecursiveFunction(int i)
{
   if (i  0) RecursiveFunction(i-1);
}

void MyFunction() { RecursiveFunction(6); }


Until, one day, I found a way to emulate them in C++:

void MyFunction()
{
   struct Local {
     static void RecursiveFunction(int i)
     {
       if (i  0) RecursiveFunction(i-1);
     }
   };

Local::RecursiveFunction(6); }


Possible uses for this construct are:
  • Recursive sub-operations within a function (shown above).
  • Callback functions that will be passed into enumerators (as in DirectDrawEnumerate()).


  • Salutaciones,
          JCAB


    The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

     

    Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
    Please read our Terms, Conditions, and Privacy information.