Reputation: 841
In C99, the compiler will issue a warning if a function is called before its declaration. For example, this will cause a warning:
int sum(const int k) {
return accsum(k, 0);
}
int accsum(const int k, const int acc) {
if (k == 0) {
return acc;
} else {
return accsum(k-1, k + acc);
}
}
int main() {
int x = sum(3);
return 0;
}
The answer I've seen after Googling is declaration is needed so that the compiler can check the parameter types to avoid errors. But why can't the compiler just go find the function definition of accsum before executing accsum when accsum is called from within sum?
Upvotes: 9
Views: 10528
Reputation: 8661
This is just a leftover from cicra 1970 C.
Forcing the programmer to declare functions before using them allows the compiler to work in one pass (i.e. read the code only once).
40 years ago it was important to limit compilation time. Today it's just an annoyance.
Edit:
Of course you must declare external function prototypes, or else the compiler has no way to know which parameters and return value to expect. This has nothing to do with the order of declaration.
The safe and convenient thing to do would be to consider undeclared external functions as errors, and dispense the programmer from forward-declaring prototypes within the same compilation unit.
As for allowing to use unprototyped functions, it is yet another circa 1970 leftover. C99 does not allow implicit declarations anymore, but you can still use K&R style declarations (a prototype without argument parameters specification).
I suppose this dangerous possibility was preserved for upward compatibility reasons.
Upvotes: 7
Reputation: 1974
Actually, it is not required that a function be declared before use in C. If it encounters an attempt to call a function, the compiler will assume a variable argument list and that the function returns int.
The reason modern compilers give warnings on an attempt to call a function before seeing a declaration is that a declaration allows the compiler to check if arguments are of the expected type. Given a declaration, the compiler can issue warnings or errors if an argument does not match the specification in the function declaration. This catches a significant percentage of errors by the programmer.
As to why the compiler doesn't look ahead for a definition, there are a few contributing factors. Firstly, there is the separate compilation model of C - there is no guarantee that there will be a function definition to be found within the current compilation unit (i.e. source file). Second, it allows the compiler to work in one pass, which increases performance. Third, it does encourage the programmer to actually declare functions (e.g. in header files) which allows for reuse with a separate compilation model. Fourth, it increases the chances of a compiler actually being able to function on machines with limited memory resources.
Upvotes: 11