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

后端 未结 15 2017
迷失自我
迷失自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 
    #include 
    
    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).

提交回复
热议问题