In C (prior to C99), you don't have to declare functions in order to use them. The compiler will assume the function takes the promoted parameter types you pass to it, and assume the function returns an int
. This, however can be quite problematic, and behavior is undefined if the function doesn't. Let's look at this:
/* file1.c */
void foo(char a, char b) {
/* doing something ... */
}
/* main.c */
int main(void) {
char a = 'a', b = 'b';
/* char variables are promoted to int
before being passed */
foo(b, a);
}
Because the types are being promoted (char -> int, float -> double
) if there is no declaration of the function at the time you call it, the arguments could not be passed at the right places in memory anymore.
Accessing b can yield to a curious value of the parameter. As a side node, the same problem occurs when you pass arguments to vararg functions
like prinft
, or functions having no prototype (like void f()
, where there is no information about the parameters types and count). This is the reason that you always have to access variadic arguments with va_arg
using their promoted type. GCC will warn you if you don't.
Always include the proper header files, so you don't run into this problems.
Edit: thanks to Chris for pointing out that char literals
(like 'a'
) are always of type int
in C