Nearby lessons
72 of 124C - Function Declaration
A function declaration — also called a prototype — tells the compiler a function's name, return type and parameter types before it is used. Learn the syntax, where prototypes go, and what breaks without them.
The Prototype Syntax
A declaration is the function's first line followed by a semicolon instead of a body:
Why the Compiler Needs It
add(3, 4) it must already know that add takes two ints and returns an int — otherwise it cannot check your arguments or generate the right code. The prototype supplies that knowledge early.Without a prototype, the call is an error in modern C:
Parameter Names Are Optional
Only the types matter to the compiler. Names are for human readers — and worth including for exactly that reason:
Use (void) for No Parameters
Empty parentheses mean "unspecified parameters" in older C, which disables argument checking. (void) means "definitely none":
Declaration vs Definition
| Declaration (prototype) | Definition | |
|---|---|---|
| Ends with | A semicolon | A body in braces |
| Contains code | No | Yes |
| How many allowed | Many (identical) | Exactly one |
| Reserves memory | No | Yes |
| Typical location | Top of file or a header | Below main or another .c file |
When You Can Skip the Prototype
If a function is defined above its first use, the definition itself acts as the declaration. This works, but stops scaling once functions call each other:
Mutual Recursion Needs Prototypes
When two functions call each other, no ordering works without a prototype — one of them must be declared first:
Prototypes in Header Files
To share functions across .c files, put the declarations in a .h file and include it everywhere. The include guard prevents duplicate declarations:
Common Mistakes
- Forgetting the semicolon —
int add(int a, int b)without;starts a definition and produces a confusing error. - Mismatched types — declaring
int f(int)then definingfloat f(float)is a conflicting-types error. - Empty parentheses —
int f();disables argument checking; writeint f(void);. - Defining a function twice — a duplicate definition is a linker error, unlike a duplicate declaration.
- Putting definitions in a header — every file that includes it gets a copy, causing multiple-definition errors.
.h file should contain prototypes, typedefs and macros — never function bodies. Put a body in a header and any project with two .c files including it will fail to link.- Syntax: returnType name(parameterTypes); — note the semicolon.
- Parameter names in a prototype are optional documentation.
- A prototype lets you define functions after main().
- Use (void) for no parameters, not empty parentheses.
- Header files collect prototypes for sharing between .c files.