C Function Declaration
A prototype is a short line that tells the compiler about a function before its full code appears. Functions so far sat above main; a prototype lets the full code sit below it instead.
A prototype above main
triple is promised above main and defined below it. The call still works, so the print shows 12.
#include <stdio.h>
int triple(int n);
int main() {
int answer = triple(4);
printf("%d\n", answer);
return 0;
}
int triple(int n) {
return n * 3;
}A void prototype
say_hello is promised above main and defined below it. The call runs the code below main, so Hello! prints.
#include <stdio.h>
void say_hello(void);
int main() {
say_hello();
return 0;
}
void say_hello(void) {
printf("Hello!\n");
}Two prototypes
Two prototypes sit above main. The prints show 13 and 7, so both calls reached the code below main.
#include <stdio.h>
int add(int a, int b);
int subtract(int a, int b);
int main() {
printf("%d\n", add(10, 3));
printf("%d\n", subtract(10, 3));
return 0;
}
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}Example
#include <stdio.h>
int cube(int n);
int main() {
printf("%d\n", cube(3));
printf("%d\n", cube(4));
return 0;
}
int cube(int n) {
return n * n * n;
}Key points
- A prototype names the return type, the function name, and the parameters.
- A prototype ends with a semicolon and has no block of code.
- Write a prototype above main when the full code sits below main.
- The prototype and the full code must agree on the name and the types.
- A call still works when only the prototype sits above main.
- A declaration tells the compiler a name exists before its full code appears.
- The full code of the function is called the definition.
The prototype above main says cube takes a whole number and sends back a whole number. Main calls cube with 3 first, so 27 prints first. Then main calls cube with 4, so 64 prints next. The full code of cube sits below main.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line is a prototype for triple?