Search code examples
c++language-designcompiler-construction

Is it generally a good idea for a compiler/interpreter to create functions while interpreting?


When I was first learning C++ I noticed that the functions are created from top to bottom unlike in languages such as Java where the order of the function "declarations" in the code does not matter.

C++ example:

#include <iostream>
using namespace std;

int main() {
    test();
    return 0;
}

void test() {

}

But when you swap the order of the functions the program works normally.

Was that intentional when C++ was designed?


Solution

  • Neither C or C++ mandates much about the order of function definitions compared to usage.

    C allows a function to be declared before usage, but (in C89/90) didn't actually require it. If a call was made to a function that hadn't been declared, the compiler was required to make certain assumptions about the function's type (and the code was invalid if the definition of the function didn't fit those assumptions).

    C++ does, however, mandates that free functions at least be declared before usage1. A function definition also declares that function, so tiny programs are often written with definitions preceding usage to avoid having to write declaration separate from their definitions.

    For class members, C++ loosens the restrictions somewhat. For example, this is perfectly acceptable:

    class Foo { 
        void bar() { baz(); }
        void baz() {}
    };
    

    Java differs primarily in simply prohibiting all free functions, so it has only member functions, which follow roughly the same rules as C++ member functions.


    1. Without this, it would be essentially impossible to support some C++ features such as function overloading.