Matching prototypes with definitions
What you'll learn: How to ensure your function's "table of contents" entry perfectly matches the actual instructions you write later in your code.
In C, a prototype is like a movie trailer—it tells the compiler the title, the stars (parameters), and the genre (return type) before the full feature begins. The definition is the movie itself. If the trailer promises a comedy starring two actors, but the movie is a silent drama with five actors, the compiler will get confused and stop the show.
The Rule of Identical Twins
For your program to compile, the signature of your prototype and the signature of your definition must be identical. Think of them as two ends of a bridge; if they aren't the exact same height and width, the bridge collapses.
Specifically, these three things must match exactly:
- Return Type: If the prototype says
int, the definition must return anint. - Function Name: The spelling and capitalization must be identical.
- Parameter List: The number of inputs, their specific data types, and their order must be the same.
Matching in Action
If you change a function later in your coding process—for example, adding a new input—you must remember to go back to the top of your file and update the prototype too.
#include <stdio.h>
// 1. THE PROTOTYPE (The Promise)
// Takes two doubles, returns one double
double calculate_tax(double price, double rate);
int main() {
double total = calculate_tax(100.0, 0.07);
printf("Tax is: %f", total);
return 0;
}
// 2. THE DEFINITION (The Fulfillment)
// This MUST match the prototype above exactly
double calculate_tax(double price, double rate) {
return price * rate;
}
If you changed the definition to double calculate_tax(double price), the compiler would throw a "conflicting types" error because the "Promise" at the top no longer matches the "Fulfillment" at the bottom.
Why Names Don't Always Matter
Interestingly, the names of the variables in the prototype don't technically have to match the definition (e.g., you could use p and r in the prototype and price and rate in the definition). However, for the sake of your sanity and readable code, you should always keep them the same. The types (double, int, char), however, are non-negotiable.
Key takeaway
A prototype and a definition must have matching return types, names, and parameter types to avoid compilation errors.