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

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

    One of the biggest reasons why this was made mandatory even in C99 (compared to C89, where you could have implicitly-declared functions) is that implicit declarations are very error-prone. Consider the following code:

    First file:

    #include 
    void doSomething(double x, double y)
    {
        printf("%g %g\n",x,y);
    }
    

    Second file:

    int main()
    {
        doSomething(12345,67890);
        return 0;
    }
    

    This program is a syntactically valid* C89 program. You can compile it with GCC using this command (assuming the source files are named test.c and test0.c):

    gcc -std=c89 -pedantic-errors test.c test0.c -o test
    

    Why does it print something strange (at least on linux-x86 and linux-amd64)? Can you spot the problem in the code at a glance? Now try replacing c89 with c99 in the command line — and you'll be immediately notified about your mistake by the compiler.

    Same with C++. But in C++ there're actually other important reasons why function declarations are needed, they are discussed in other answers.

    * But has undefined behavior

提交回复
热议问题