C/C++ Arena

Step 4 of 7

Prototypes

The compiler reads your file once, from top to bottom. When it reaches a call like half(10), it needs to already know what half is: its return type and the types of its parameters. If the definition comes further down the file, the compiler hasn't seen it yet and reports an error such as call to undeclared function 'half'.

You have two options:

  1. Define every function above the functions that call it.
  2. Put a prototype (also called a declaration) near the top: the function's first line, ending with a semicolon instead of a body.
#include <stdio.h>

double area(double w, double h);

int main(void) {
    printf("%.1f\n", area(2.5, 4));
    return 0;
}

double area(double w, double h) {
    return w * h;
}
10.0

The prototype promises "a function called area exists, takes two doubles and returns a double". That's enough for the compiler to check the call in main. The actual body can come later in the file, or even in a different file.

Why prototypes matter

In bigger programs, functions call each other in every direction, so no ordering works for all of them. Prototypes also go in header files (.h), which is how one file uses functions defined in another. #include <stdio.h> is exactly that: a file full of prototypes, including printf's.

The prototype and the definition must match. If they disagree about types, the compiler reports conflicting types.

Your turn: press Check to see the error, then add the missing prototype.

Previous: void functions Next: Scope and pass by value