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

后端 未结 6 1488
余生分开走
余生分开走 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:21

    As to why your declaration of

    void f() {
        void g(); g();
    }
    

    is better than this one

    void g();
    void f() {
        g();
    }
    

    It's generally good if you keep declarations as local as possible, so that as few name clashes as possible result. I say it's arguable whether declaring a function locally (this way) is really fortunate, as i think it's still better to ordinary include its header and then go the "usual" way, which is also less confusing to people not knowing about that. Sometimes, it's also useful to work around a shadowed function

    void f() {
        int g; 
        // oops, ::g is shadowed. But we can work around that
        {
            void g(); g();
        }
    }
    

    Of course, in C++ we could call function g using its_namespace::g() - but in the old days of C, that wouldn't have been possible, and that thing allowed the programmer to still access the function. Also note that while syntactically it is not the same, semantically the following does also declare a function within a local scope, that actually targets a different scope.

    int main() {
        using std::exit;
        exit();
    }
    

    As a side note, there are more situations like that where the target scope of a declaration is not the scope where that declaration appears in. In general, the entity you declare becomes a member of the scope in which the declaration appears. But that's not always the case. Consider for example friend declarations, where that thing happens

    struct X { friend void f() { std::cout << "WoW"; } };
    int main() { void f(); f(); } // works!
    

    Even though the function declaration (and definition!) of f happened within the scope of X, the entity (the function itself) became a member of the enclosing namespace.

提交回复
热议问题