...
In this noncompliant code example, which involves two files, the definition of func()
file_a.c
expects three parameters but is supplied only two. However, because there is no prototype for func()
in the second file, the compiler assumes that the correct number of arguments has been supplied and uses the next value on the program stack as the missing third argument.
Code Block |
---|
|
/* file_a.c source file */
int func(int one, int two, int three){
printf("%d %d %d", one, two, three);
return 1;
}
|
However, because there is no prototype for func()
in file_b.c
, the compiler assumes that the correct number of arguments has been supplied and uses the next value on the program stack as the missing third argument.
Code Block |
---|
|
/* file_b.c source file */
func(1, 2);
|
Wiki Markup |
---|
C99 eliminated implicit function declarations from the C language \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]. However, many compilers still allow compilation of programs containing implicitly declared functions, although they may issue a warning message. These warnings should be resolved (see [MSC00-C. Compile cleanly at high warning levels]). |
...
To correct this example, the appropriate function prototype for func()
should must be specified in the file in which it is invoked. This allows the compiler to diagnose invalid function arguments:
Code Block |
---|
|
/* file_b.c source file */
int func(int, int, int);
func(1, 2);
|
Compliant Solution (Function Prototypes)
This compliant solution correctly includes the function prototype for func()
in the compilation unit in which it is invoked, and the function invocation has been corrected to pass the right number of arguments.The user can then correct the code:
Code Block |
---|
|
int func(int one, int two, int three){
printf("%d %d %d", one, two, three);
return 1;
}
|
Code Block |
---|
|
/* file_b.c source file */
int func(int, int, int);
func(1, 2, 3);
|
DCL14-C shows how to use header files to accomplish this same goal in a more maintainable fashion.
Noncompliant Code Example (Function Pointers)
...