Lesson 77 +10 XP

Function Prototypes (Declaration)

Function Prototypes (Declaration)

A prototype tells the compiler about a function before its full definition, so you can use the function first and define it later.

The problem

Calling a function before defining it causes a warning/error. The fix: declare the function with a prototype.

Prototype vs definition

// Prototype (declaration)
int add(int a, int b);

int main() {
    printf("%d", add(3, 4));   // works now
    return 0;
}

// Definition
int add(int a, int b) {
    return a + b;
}

The prototype line

It's exactly the function's first line with a semicolon:

returnType name(parameters);

Where it lives

Usually at the top of the file (or in a header) before any call.

TL;DR

  • A prototype is the function's signature ending in ;.
  • It lets you call a function before its definition.
  • Definitions can come later in the file.
  • Great for organizing large programs.