Why do functions need to be declared before they are used?

后端 未结 11 766
挽巷
挽巷 2020-11-29 06:06

When reading through some answers to this question, I started wondering why the compiler actually does need to know about a function when it first encounters it. Wo

11条回答
  •  离开以前
    2020-11-29 06:35

    I think of two reasons:

    • It makes the parsing easy. No extra pass needed.
    • It also defines scope; symbols/names are available only after its declaration. Means, if I declare a global variable int g_count;, the later code after this line can use it, but not the code before the line! Same argument for global functions.

    As an example, consider this code:

    void g(double)
    {
        cout << "void g(double)" << endl;
    }
    void f()
    {
        g(int());//this calls g(double) - because that is what is visible here
    }
    void g(int)
    {
        cout << "void g(int)" << endl;
    }
    int main()
    {
        f();
        g(int());//calls g(int) - because that is what is the best match!
    }
    

    Output:

    void g(double)
    void g(int)

    See the output at ideone : http://www.ideone.com/EsK4A

提交回复
热议问题