tags:

views:

73

answers:

4

Does it matter if the function definition is before the int (main) or after the int main?

I've seen it both ways and am trying to find the proper way to display the function definition and declaration.

+6  A: 

No .. it doesn't. Its a matter of preference. Choose which you prefer and be consistent!

Goz
That tends to be the usual answer when it comes to style questions. Should I choose style A or style B? Simply choose one and stick with it.
AndyPerfect
For sure. I'm a huge proponent of consistency :)
Goz
+2  A: 

The function definition (which contains the actual code) can be anywhere, even in a different file, as long as the declaration (the function prototype) appears before you call the function.

casablanca
(The comment above seems to have disappeared, but I'll leave my reply here.) You could very well place it in another `.cpp` file as long as you link them together when compiling. And no, contrary to what you said, it's actually good practice because it makes it easier to manage things once you have more than a few functions to deal with.
casablanca
@casablanca: I assume you're referring to the function definitions here, because if you're talking about `#include`ing .cpp files so you don't need to put the declarations in, I'm going to be very disappointed in you.
David Thornley
Oh my, I would never `#include` a source file. That's why I mentioned "link them together".
casablanca
@casablanca: I didn't think you'd `#include` a source file, but I do think you used an unspecified antecedent: the first "it" in your earlier comment.
David Thornley
I see what you mean. :) It's too late to edit the comment now, but I guess your comment makes the point clear.
casablanca
A: 

The function definition can be before or after main or even in a different file. What is necessary is that a declaration (or 'prototype') of the function is before the code that uses the function.

Where you put your code can have an effect on compile times. If all the code is in one file, it takes longer to recompile a small change, but if you put code in different files, a small change can take less time to recompile into the executable.

JoshD
+1  A: 

It is basically a matter of preference. The only requirement is that function declarations (not definitions) precede calls to the function.

As a matter of style, I would generally keep the function definition with the function declaration unless there is a reason to separate them. Which implies that all function definitions would come before the main() definition.

Dave Costa