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

后端 未结 11 1893
陌清茗
陌清茗 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:37

    Well, the answer is "historical reasons". In C you could have function declarations at block scope, and the C++ designers did not see the benefit in removing that option.

    An example usage would be:

    #include 
    
    int main()
    {
        int func();
        func();
    }
    
    int func()
    {
        std::cout << "Hello\n";
    }
    

    IMO this is a bad idea because it is easy to make a mistake by providing a declaration that does not match the function's real definition, leading to undefined behaviour which will not be diagnosed by the compiler.

提交回复
热议问题