Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Can we have functions inside functions in C++?

I mean something like:

int main() 
{
  void a() 
  {
      // code
  }
  a();

  return 0;
}

Answer*

Cancel
10
  • 1
    Should be operator () (unsigned int val), your missing a set of parentheses.
    – Joe D
    Commented Dec 1, 2010 at 14:55
  • 1
    Actually, this is a perfectly reasonable thing to do if you need to pass this functor to an stl function or algorithm, like std::sort(), or std::for_each().
    – Dima
    Commented Dec 1, 2010 at 16:18
  • 1
    @Dima: Unfortunately, in C++03, locally defined types cannot be used as template arguments. C++0x fixes this, but also provides the much nicer solutions of lambdas, so you still wouldn't do that.
    – Ben Voigt
    Commented Dec 2, 2010 at 20:31
  • Oops, you are right. My bad. But still, this is not just a funny trick. It would have been a useful thing if it were allowed. :)
    – Dima
    Commented Dec 2, 2010 at 20:34
  • 3
    Recursion is supported. However, you can't use auto to declare the variable. Stroustrup gives the example: function<void(char*b, char*e)> rev=[](char*b, char*e) { if( 1<e-b ) { swap( *b, *--e); rev(++b,e); } }; for reversing a string given begin and end pointers.
    – Eponymous
    Commented Aug 20, 2014 at 15:11