Will Perone

Remember in PASCAL when you could have those cool local function definitions? It's too bad C++ doesn't have anything like that.... or does it? Here is a presentation of 3 different methods of how to pull it off:

Method 1, an example of a local recursive function:
void MyFunction()
{
   struct Local 
   {
     static void RecursiveFunction(int i)
     {
       if (i > 0) RecursiveFunction(i-1);
     }
   };

   Local::RecursiveFunction(6);
}

Method 2, an example of a local function with a reference counter using a function object:
int main() 
{
  struct Function 
  {
    int numCalls;

    Function() : numCalls(0) { }

    const int operator()(const int i, const int j) 
    {
      ++this->numCalls;
      return i + j;
    }
  } function;

  std::cout << function( 1, 2 ) << std::endl;
  std::cout << function( 3, 4 ) << std::endl;

  std::cout << function.numCalls << std::endl;

  return 1;
}

Method 3: Local recursive function via function object
void MyFunction()
{
  struct Recursive 
  {
    void operator()(int i) 
    {
        if (i > 0) 
        {
           (*this)(i-1);
        }
    }
  } recursive;

  recursive(6);
}
2 Comments
jmd 0 0
What the use of the const in "const int operator()(const int i, const int j)" ?

Aren't you making that function const whilst it basically isn't ? (modifying this->numCalls)
Jay 0 0
The initial const int "const int operator..." refers to the int, not the method. It is unnecessary since the int is returned by value.

FWIW, you don't actually have to give the local struct a name if you are going to create a single instance as above:

void MyFunction()
{
struct
{
void operator()(int i)
{
if (i > 0)
{
(*this)(i-1);
}
}
} recursive;

recursive(6);
}


<- for private contact