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

后端 未结 11 736
挽巷
挽巷 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)!

    0 讨论(0)
  • 2020-11-29 06:39

    I remember with Unix and Linux, you have Global and Local. Within your own environment local works for functions, but does not work for Global(system). You must declare the function Global.

    0 讨论(0)
  • 2020-11-29 06:40

    Because C and C++ are old languages. Early compilers didn't have a lot of memory, so these languages were designed so a compiler can just read the file from top to bottom, without having to consider the file as a whole.

    0 讨论(0)
  • 2020-11-29 06:44

    I guess because C is quite old and at the time C was designed efficient compilation was a problem because CPUs were much slower.

    0 讨论(0)
  • 2020-11-29 06:49

    Since C++ is a static language, the compiler needs to check if values' type is compatible with the type expected in the function's parameters. Of course, if you don't know the function signature, you can't do this kind of checks, thus defying the purpose of a static compiler. But, since you have a silver badge in C++, I think you already know this.

    The C++ language specs were made right because the designer didn't want to force a multi-pass compiler, when hardware was not as fast as the one available today. In the end, I think that, if C++ was designed today, this imposition would go away but then, we would have another language :-).

    0 讨论(0)
提交回复
热议问题