Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible in C or C++ to create a function inside another?

Tags:

c++

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,

like image 200
make Avatar asked Feb 13 '10 06:02

make


Video Answer


2 Answers

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.

like image 172
Potatoswatter Avatar answered Sep 21 '22 23:09

Potatoswatter


C++ does not support nested functions, however you can use something like boost::lambda.

like image 24
Xorlev Avatar answered Sep 19 '22 23:09

Xorlev