Function prototypes
- C course
- Beginner
- Lesson 68/116
- 5 min
Learn function prototypes (declarations) and ordering.
Function prototype
A prototype is a line that declares a function's signature in advance. It tells the compiler "this function is defined further down".
int add(int, int); /* prototype */
int main(void) {
int s = add(2, 3);
return 0;
}
int add(int a, int b) { /* definition */
return a + b;
}Without a prototype, if the definition comes after main, the compiler warns. In modern C, headers included with #include also contain prototypes.
Headers and prototypes
Lines like #include <stdio.h> add prototypes of library functions to your file. This is why you can call printf without defining it.
#include <stdio.h>
int main(void) {
printf("%d\n", 42); /* prototype comes from stdio.h */
return 0;
}When using standard library functions, you must include the relevant header; otherwise the compiler may assume a wrong return type.
Practice Prototype and definition together
Write the int square(int); prototype before main. In main, call printf("%d\n", square(5));. After main, define int square(int x) { return x * x; }. Output should be 25.
Starter code
#include <stdio.h>
/* square prototype */
int main(void) {
/* call printf %d with square(5) */
return 0;
}
/* square definition */Sample solution
#include <stdio.h>
int square(int);
int main(void) {
printf("%d\n", square(5));
return 0;
}
int square(int x) {
return x * x;
}Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a function prototype do?
- Tells the compiler the signature in advance Correct answer
- Speeds up the function
- Makes the function callable
- Renames the function
Explanation: A prototype tells the compiler the function signature in advance.
2 Prototype line
int add(int, ____); /* prototype */
int add(int, int); /* prototype */
Explanation: In a prototype, only the type is needed; the name is optional.
3 Match prototype concepts
| Term | Meaning |
|---|---|
int add(int, int); |
prototype |
int add(int a, int b) { |
definition start |
add(2, 3); |
call |
#include <stdio.h> |
header |