I know that it's poor practice to not include function prototypes, but if you don't, then the compiler will infer a prototype based on what you pass into the function when you call it (according to this answer). My question is why does the compiler infer the prototype from what you pass into the function rather than the definition of the function itself? I can imagine some kind of preprocessing step where all declared functions are identified and checked to see if a prototype exists for each one. If one doesn't have a prototype, the first line of the function is copied and stuck under the existing prototypes. Why isn't this done?
-
3Mainly because the inference can be wrong, and determining the correct const-ness for the type is tricky too. – Jonathan Leffler Aug 15 '14 at 15:25
-
You know what the purpose of prototypes are, right? – Fiddling Bits Aug 15 '14 at 15:27
-
2If the function definition is visible at the call point, the function type *is* inferred from the definition. And as of C99, the compiler doesn't infer the function type from a call; calling a function with no visible declaration is a constraint violation. (The declaration doesn't have to be a prototype.) – Keith Thompson Aug 15 '14 at 15:46
2 Answers
Because the C compiler was designed as a single pass compiler, where any given file does not know about the other source files that make up the project.
Although compilers have gotten more sophisticated, and may do multiple passes, the general outline of the compilation process framework remains as it was in K&R's day:
- Pre-process each source file(macro text replacement only).
- Compile the processed source into an object file.
- Link the objects into an executable or library.
Inferring prototypes would have to happen in the first step, but the compiler does not know about the existence of any other objects which may contain the function definition at that time.
It might be possible to make a compiler which did what you suggest, but not without breaking the existing rules for how to infer prototypes. A change with such big consequences would make the language no longer C.

- 34,686
- 15
- 91
- 152
The major use for prototypes is to declare a function and inform the compiler about the number and type of arguments in cases where the definition is not visible. Since C was originally compiled single-pass, the definition is not visible when it occurs later in the translation unit, but the more important case from a modern perspective is when the definition is not visible at all, due to lying in a separate translation unit, possibly even in a library file that exists only in compiled form and where no information about the function's type is recorded.

- 208,859
- 35
- 376
- 711