Why can't I define a function inside another function?

后端 未结 11 1895
陌清茗
陌清茗 2020-11-27 16:55

This is not a lambda function question, I know that I can assign a lambda to a variable.

What\'s the point of allowing us to declare, but not define a function insid

11条回答
  •  半阙折子戏
    2020-11-27 17:29

    In the example you give, void two(int) is being declared as an external function, with that declaration only being valid within the scope of the main function.

    That's reasonable if you only wish to make the name two available within main() so as to avoid polluting the global namespace within the current compilation unit.

    Example in response to comments:

    main.cpp:

    int main() {
      int foo();
      return foo();
    }
    

    foo.cpp:

    int foo() {
      return 0;
    }
    

    no need for header files. compile and link with

    c++ main.cpp foo.cpp 
    

    it'll compile and run, and the program will return 0 as expected.

提交回复
热议问题