One complete example
A prototype example is a short program that declares a function above main and defines it below. This program adds two numbers:
#include <iostream>
int add(int a, int b); // prototype
int main() {
std::cout << add(2, 3) << '\n'; // prints 5
return 0;
}
int add(int a, int b) { // definition
return a + b;
}
Output:
5
Here is what each part does:
- The prototype
int add(int a, int b);tells the compiler the name, return type and parameter types ofadd. - The call
add(2, 3)insidemainis checked against that prototype. - The definition below
main, covered in what is a function definition, supplies the code that adds the numbers.
If functions themselves are new to you, start with what is a function in c.
A function that returns nothing
When a function returns no value, its prototype uses void:
#include <iostream>
#include <string>
void print_line(const std::string& text); // prototype
int main() {
print_line("Prototypes come first.");
return 0;
}
void print_line(const std::string& text) { // definition
std::cout << text << '\n';
}
Output:
Prototypes come first.
Several prototypes in one file
A file can declare many functions before main:
#include <iostream>
int add(int a, int b);
int subtract(int a, int b);
int main() {
std::cout << add(7, 2) << '\n'; // prints 9
std::cout << subtract(7, 2) << '\n'; // prints 5
return 0;
}
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
Output:
9
5
What a mismatch looks like
If the prototype and the definition disagree, the compiler reports an error. In this example the prototype returns int, but the definition returns double:
int square(int x);
double square(int x) { // error: conflicts with the prototype
return x * x;
}
The fix is to make the two return types match.
A call with too few arguments
The prototype also tells the compiler how many arguments a call must supply:
int add(int a, int b);
int main() {
int total = add(1); // error: too few arguments
return total;
}
Add the missing argument, such as add(1, 2), and the call compiles.
Checklist for your own prototypes
- Match the name, return type and parameter types of the definition.
- End the prototype with a semicolon.
- Place it above the first call, or in a header file if the program has several files. What is a .h file explains that file type.
- Include parameter names if they help readers. They are optional.
A prototype can also describe a parameter that is itself a function, a topic covered in c pass function as argument.
Summary
A prototype example shows the same pattern every time: a declaration above the code that uses the function, and the definition below. Once you can read the prototype line, you can predict what the compiler will accept and what it will reject.