function understanding

what is better in a program "writing and executing" while using the function is to declare the function before main and write the definition after main? or write the declaration and definition before main? what is the advantage and disadvantage of both methods? i prefer to write the declaration and definition of function before the main.
thanks a lot.
regards.
semsemdiver

In my opinion, it's just individual/team preference and nothing more. I find it more consistent to have a .cpp file with [Name of overall project].cpp or main.cpp, and have int main() { } at the end of that file, so that I know exactly where to look. Other people prefer to have main be the very first function in the file, because that's the first thing that will lrun.

If you write the definition of the function before main, it doesn't need its own, separate declaration (the two are implicitly combined). If you choose to write main first, then you need to put function declarations at the top.
For small test programs I usually write functions in such an order that I don't have to write a lot of extra function declarations, with main() at the bottom.

In more serious projects, with multiple files, main() is usually in its own file.

One advantage of getting into the habit of declaring functions at the top could be that it prepares you for when you start splitting functions into multiple files (those function declarations are essentially what would go into the header files).
Last edited on
Ganado
peter87


Thanks a lot
best regards.
semsemdiver
Topic archived. No new replies allowed.