Search code examples
c++program-entry-pointforward-declarationcode-organization

Why can I not define main() first, and then the functions which it calls?


If I put main on the top of the source file and invoke some custom functions, it will tell me that those functions are not found, but if I put main on the bottom of the source file, it will work.

Why? Is it because the compiler parses the program from top to bottom and breaks at the definition of main?


Solution

  • It has nothing to do with main. C++ compilers work top to bottom, period.

    Anything that you reference needs to be declared previously. The same goes for variables. In your case, you could do

    void foo();     // <-- Forward declaration, aka prototype
    
    int main() {
       foo();
    }
    
    void foo() {
       // Here is your foo implementation.
    }