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

后端 未结 11 784
挽巷
挽巷 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:36

    Still, you can have a use of a function before it is declared sometimes (to be strict in the wording: "before" is about the order in which the program source is read) -- inside a class!:

    class A {
    public:
      static void foo(void) {
        bar();
      }
    private:
      static void bar(void) {
        return;
      }
    };
    
    int main() {
      A::foo();
      return 0;
    }
    

    (Changing the class to a namespace doesn't work, per my tests.)

    That's probably because the compiler actually puts the member-function definitions from inside the class right after the class declaration, as someone has pointed it out here in the answers.

    The same approach could be applied to the whole source file: first, drop everything but declaration, then handle everything postponed. (Either a two-pass compiler, or large enough memory to hold the postponed source code.)

    Haha! So, they thought a whole source file would be too large to hold in the memory, but a single class with function definitions wouldn't: they can allow for a whole class to sit in the memory and wait until the declaration is filtered out (or do a 2nd pass for the source code of classes)!

提交回复
热议问题