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

后端 未结 15 1929
迷失自我
迷失自我 2020-12-15 09:18

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(){
     ...
            


        
相关标签:
15条回答
  • 2020-12-15 09:46

    Not in standard C, but gcc and clang support them as an extension. See the gcc online manual.

    0 讨论(0)
  • 2020-12-15 09:46

    Though C and C++ both prohibit nested functions, a few compilers support them anyway (e.g., if memory serves, gcc can, at least with the right flags). A nested functor is a lot more portable though.

    0 讨论(0)
  • 2020-12-15 09:48

    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.

    0 讨论(0)
  • 2020-12-15 09:50

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

    0 讨论(0)
  • 2020-12-15 09:50

    No nested functions in C/C++, unfortunately.

    0 讨论(0)
  • 2020-12-15 09:51

    you can't create a function inside another function in C++.

    You can however create a local class functor:

    int foo()
    {
       class bar
       {
       public:
          int operator()()
          {
             return 42;
          }
       };
       bar b;
       return b();
    }
    

    in C++0x you can create a lambda expression:

    int foo()
    {
       auto bar = []()->int{return 42;};
       return bar();
    }
    
    0 讨论(0)
提交回复
热议问题