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

后端 未结 15 1928
迷失自我
迷失自我 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:27

    Clang/Apple are working on 'blocks', anonymous functions in C! :-D

    ^ ( void ) { printf("hello world\n"); }

    info here and spec here, and ars technica has a bit on it

    0 讨论(0)
  • 2020-12-15 09:31
    void foo()
    {
        class local_to_foo 
        { 
             public: static void another_foo() 
             { printf("whatevs"); } 
        };
        local_to_foo::another_foo();
    }
    

    Or lambda's in C++0x.

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

    It is not possible to declare a function within a function. You may, however, declare a function within a namespace or within a class in C++.

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

    As other answers have mentioned, standard C and C++ do not permit you to define nested functions. (Some compilers might allow it as an extension, but I can't say I've seen it used).

    You can declare another function inside a function so that it can be called, but the definition of that function must exist outside the current function:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main( int argc, char* argv[])
    {
        int foo(int x);
    
        /*     
        int bar(int x) {  // this can't be done
            return x;
        }
        */
    
        int a = 3;
    
        printf( "%d\n", foo(a));
    
        return 0;
    }
    
    
    int foo( int x) 
    {
        return x+1;
    }
    

    A function declaration without an explicit 'linkage specifier' has an extern linkage. So while the declaration of the name foo in function main() is scoped to main(), it will link to the foo() function that is defined later in the file (or in a another file if that's where foo() is defined).

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

    The term you're looking for is nested function. Neither standard C nor C++ allow nested functions, but GNU C allows it as an extension. Here is a good wikipedia article on the subject.

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

    C — Yes for gcc as an extension.

    C++ — No.

    0 讨论(0)
提交回复
热议问题