Reputation: 131
Does placing functions after main have any affect on the program compared with placing them before main?
Example — after:
void foo(void);
int main(void){
…
}
void foo(void){
…
}
Example — before:
void foo(void){
…
}
int main(void){
…
}
Upvotes: 2
Views: 4925
Reputation: 753695
Assuming you use old C (C99) or new C (C11) and not either ancient C (C90) or ante-diluvian C (pre-standard C), then the advantage of defining functions before main()
is that you don't need to separately specify the prototypes of those functions — the definition also specifies the prototype.
If the functions defined in the file containing main()
are also used in other source files, then you'd have a header declaring the functions anyway, and that header would be used in both the file containing main()
and in the other source files.
If, as is probably the case, the functions are only used in the file containing main()
, then you'd ensure that the functions are defined as static
.
If you place the function definitions after main()
, you must declare the functions before they're used (e.g. by main()
). This is a consequence of not using ancient or ante-diluvian C — all functions must be declared before being used.
Note that defining a function like this does not declare a prototype for the function:
void somefunc()
{
…operations…
}
It provides a declaration for the function, but it does not provide a prototype. That means you can miscall it:
somefunc(1);
somefunc("a", "z");
and the compiler is not required to complain about the misuse. (The rules in C++ are different in this regard — all function definitions provide a prototype. C had a legacy code base that C++ did not have which prevented that from being a sensible rule for C — so, the C standard committee being sensible people, the C standard does not include the non-sensible rule.)
To make that into a prototype, you must write:
void somefunc(void)
{
…operations…
}
So, if functions are properly defined before main()
, you don't need to repeat their declaration. If you define the functions after main()
, those functions called directly from main()
must have a declaration (and should have a prototype declaration) in scope before main()
is defined.
Note that you should not declare functions within other functions, regardless of how permissible that is. Such 'hidden' declarations are a major maintenance liability. The declarations should be at file scope, usually at the top of the file or in a header.
Assuming you write in modern C:
main()
.Upvotes: 8