Nested functions are not allowed but why nested function prototypes are allowed? [C++]

后端 未结 6 1486
余生分开走
余生分开走 2020-12-30 12:57

I was reading the linked question which leads me to ask this question.

Consider the following code

int main()
{
    string SomeString();
}
         


        
6条回答
  •  误落风尘
    2020-12-30 13:17

    When you declare a prototype as you are doing you are basically telling the compiler to wait for the linker to resolve it. Depending where you write the prototype the scoping rules apply. There is nothing technically wrong writing the prototype inside your main() function (although IMHO a bit messier), it just means that the function is only locally known inside the main(). If you would have declared the prototype at the top of your source file (or more commonly in a header file), the prototype/function would be known in the whole source.

    string foo()
    {
      string ret = someString();  // Error
      return ret; 
    }
    
    int main(int argc,char**argv)
    {
       string someString();
       string s = somestring(); // OK
       ...
    }
    

提交回复
热议问题