TOPIC 9.1.2
Order of Functions


Sometimes the question arises of why does C++ order functions with the main function first and the other functions following. This question is most commonly raised by those who have used languages that order functions another way, such as Pascal. The C and C++ style of ordering functions is more a matter of standardization than anything else. There is no reason that the main function in a C++ program cannot be at the bottom of a program. However, that is discouraged because source code is expected to follow the standard style of placing the main function at the top of the program.

As a compiler works its way through a program, it must have knowledge of each variable and function name it runs across. For example, you know that you cannot refer to a variable until it has been declared, and you must declare the variable above the point in the code where the variable is first used. The same is true of functions. When a function appears in the source code, it must have been declared prior to its use.

That is why the function prototypes appear at the top of the program. The compiler reads the function prototypes before it ever gets to the main function. That way, when the compiler sees the function name in the main function or in other functions below, it will be aware of the function, even though the actual function may not appear until the end of the program.

If functions were re-ordered in a C++ function so that main appeared last and each function appeared before the point that it was called, then there would be no need for function prototypes. Programs are generally more readable and better organized, however, when the function prototypes appear at the top. In Pascal, the forward declaration would be similar to a function prototype.

The main function does not require a prototype. It is said to be self prototyping. The compiler knows that the program always starts in the main function, so there is no need to declare it ahead of time. Also, regardless of where the main function is located, it will execute first.