What is the difference between function declaration and definition in C?
Function declaration (prototype): Tells the compiler the function's name, return type, and parameter types. Does NOT include the body. Ends with a semicolon.
Function definition: Provides the actual body (implementation) of the function.
Why declarations matter:
- In C, you must declare a function before calling it (or define it before the call).
- Declarations are typically placed in header files (.h) so multiple source files can use the function.
- Without a declaration, C89 assumes the function returns
intand accepts any arguments (implicit declaration). C99+ makes implicit declarations an error.
Declaration syntax: return_type function_name(param_types);
- Parameter names are optional in declarations:
int add(int, int);is valid. - But parameter names in declarations improve readability:
int add(int a, int b);.
Declaration (prototype):
int add(int a, int b); // tells compiler about function
Definition:
int add(int a, int b) { // provides the implementation
return a + b;
}
1. Declaration before first use (or definition before use)
2. Declarations go in header files (.h)
3. Definitions go in source files (.c)
4. One definition allowed (ODR), multiple declarations OK
#include <stdio.h>
/* Declaration (prototype) -- no body, ends with ; */
int add(int a, int b);
int multiply(int, int); /* parameter names optional */
int main(void) {
/* Can call add() and multiply() because they are declared above */
printf("add(3, 4) = %d\n", add(3, 4)); /* 7 */
printf("mul(3, 4) = %d\n", multiply(3, 4)); /* 12 */
return 0;
}
/* Definition -- provides the body */
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
- •Declaration = signature only (no body, ends with ;)
- •Definition = signature + body (the implementation)
- •Declare before use; define once in a .c file
- •Declarations go in .h files; definitions in .c files
- •C99+ requires explicit declaration before calling a function
- •C89 allows implicit declarations (assumes int return) -- C99+ makes this an error
- •Declaring int f() means f takes UNSPECIFIED parameters, not zero; use int f(void) for zero
- •Multiple declarations are fine; multiple definitions cause a linker error
- •Forgetting to include the header with the prototype can cause implicit declaration warnings