Search code examples
c++functionconventionsprocedures

C++ Function Conventions?


Just had a 'Fundamentals of Programming' lecture at uni and was told that the convention for using/declaring functions is to have the main() function at the top of the program, with functions/procedures below it and to use forward declarations to prevent compiler errors.

However, I've always done it the other way - functions at top main() at bottom and not using forward declarations and don't think I've ever seen it otherwise.

Which is right? Or is it more a case of personal preference? Some clarification would be hugely appreciated.


Solution

  • There could be the case when your functions are related to each other. If you simply write them above the main() without forward-declaration you have to order them so they'll know the functions they depend on. In some cases (circular references) it won't even be possible to compile without forward declaration.

    When forward declaring the functions you won't run into this issue.

    Additionally when having main() as first function, you'll produce more readable code, but thats perhaps just personal preference.
    It could also be more readable cause another coder has on overview about the functions he'll find in the file.