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

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

    The C programming language was designed so that the compiler could be implemented as a one-pass compiler. In such a compiler, each compilation phase is only executed once. In such a compiler you cannot referrer to an entity that is defined later in the source file.

    Moreover, in C, the compiler only interpret a single compilation unit (generally a .c file and all the included .h files) at a time. So you needed a mechanism to referrer to a function defined in another compilation unit.

    The decision to allow one-pass compiler and to be able to split a project in small compilation unit was taken because at the time the memory and the processing power available was really tight. And allowing forward-declaration could easily solve the issue with a single feature.

    The C++ language was derived from C and inherited the feature from it (as it wanted to be as compatible with C as possible to ease the transition).

提交回复
热议问题