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

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

    Specifically answering this question:

    From the answers it seems that there in-code declaration may be able to prevent namespace pollution, what I was hoping to hear though is why the ability to declare functions has been allowed but the ability to define functions has been disallowed.

    Because consider this code:

    int main()
    {
      int foo() {
    
        // Do something
        return 0;
      }
      return 0;
    }
    

    Questions for language designers:

    1. Should foo() be available to other functions?
    2. If so, what should be its name? int main(void)::foo()?
    3. (Note that 2 would not be possible in C, the originator of C++)
    4. If we want a local function, we already have a way - make it a static member of a locally-defined class. So should we add another syntactic method of achieving the same result? Why do that? Wouldn't it increase the maintenance burden of C++ compiler developers?
    5. And so on...

提交回复
热议问题