C/C++ – Creating Functions Inside Another Function

c++

Could someone please tell me if this is possible in C or C++?

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   int fun_b(){
     ...
   }
   ...
} 

or something similar, as e.g. a class inside a function?

thanks for your replies,

Best Answer

Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   struct { int operator()() {
     ...
   } } fun_b;

   int q = fun_b();
   ...
}

You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.

Related Question