Why should I prototype functions?

I understand defining the function, but wouldn't it be easier to code and more legible for the reader if one simply defined the function at the top of the program?
Not necessarily. When I want to start reading program code, I generally want to start with main(), not with a thousand helper functions. However, it would help readability if you moved all declarations into headers and the definitions to their appropriate source files.
If you have one translation unit and your functions are small enough then it is indeed better to put definitions of functions before their usage. Though in general it is a matter of taste. Functions can be very large and will make hard to see other definitions in the translation unit which also are placed at the top of the program.
But usually the same functions are used in several modules. And because there must be only one definition of every function in the program their declarations (prototypes) are placed in a header and their definitions are put in a separate module.
If you have one translation unit and your functions are small enough then it is indeed better to put definitions of functions before their usage.


Actually, I'm with Athar here. If I have a single source file, the main function should be the first one to be defined. Even small functions can take a way quite a bit of space.

ex: I'm currently working on another tetris clone. I have over 50 lines of function declarations, struct definitions, includes and the like before the main function already. Most of the functions are between 1 and 5 lines, the longest being like 15 lines or so, but even putting only those on top would bury the main function under a giant pile of helper functions that make no sense without the context they're used in. (And yeah, I AM going to split this up later and make sure that only those functions that are actually needed in the main unit are visible there, but I'll save that kind of work for later)
I prefer to put the function definitions first, personally, because it forces me to take stock of how many functions I have, and decide whether it's too much and needs to be split into another file or not.
Well yeah, but splitting declaration and definition actually makes it easier to split into other files...
Also, I can collapse my functions and loops...I know that that's not actually universal, but Netbeans and Code::Blocks for sure give that ability. Doesn't help anyone else reading my code, though, if they're using a different IDE. :p
It matters to prototype because it lets the compiler know they're there. If you're just starting out, then you won't notice it, but when you get to bigger projects, it becomes essential that you prototype all functions

Topic archived. No new replies allowed.