C ยท Chapter 27 of 45

C Function Declaration (Prototypes)

A function declaration, or prototype, tells the compiler a function's name, return type, and parameter types before it's actually defined or used. This allows you to call a function before its full definition appears in the file.

Prototypes are especially important when functions call each other, or when definitions live in separate source files and are shared via header files.

Syntax
returnType functionName(paramTypes);

Why prototypes are needed

The C compiler processes code from top to bottom, so if you call a function before it's defined, the compiler needs a prototype to know its signature and check your call for correctness.

Declaration vs definition

A declaration just states the function's signature and ends with a semicolon (no body). A definition provides the full body and does the actual work.

Example 1 (c)
#include <stdio.h>

int add(int a, int b);

int main() {
  printf("%d\n", add(2, 3));
  return 0;
}

int add(int a, int b) {
  return a + b;
}
Output
5

The prototype lets main() call add() even though add() is defined afterward.

Example 2 (c)
// math_utils.h
int square(int n);
Output
(no output โ€” header file)

Header files typically contain only function prototypes, shared across multiple .c files.

Key points

  • A prototype declares a function's signature without its body.
  • Prototypes let you call functions before they're fully defined.
  • Header files (.h) commonly store prototypes shared across files.
  • A prototype and its definition must have matching signatures.
๐Ÿ’ก Note: Mismatched prototypes and definitions are a common source of confusing compiler warnings.

๐Ÿ“ Quick Quiz

1. What does a function prototype typically end with?

2. Why are prototypes useful?

3. Where are prototypes commonly stored for sharing across files?