Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Function Declaration and Definition

The C compiler reads a file from top to bottom. When it meets a call to a function, it must already know the function's name, parameters and return type. That is why in earlier examples the functions were written above main.

Declaration and definition

A definition is the whole function with its body. A declaration, also called a prototype, is only the first line followed by a semicolon. It tells the compiler "this function exists and looks like this", so the definition can come later.

#include <stdio.h>

// Declarations (prototypes)
int add(int a, int b);
void printResult(const char *label, int value);

int main(void) {
    int sum = add(17, 25);
    printResult("Sum", sum);
    return 0;
}

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

void printResult(const char *label, int value) {
    printf("%s: %d\n", label, value);
}
Output
Sum: 42

Many programmers prefer this layout: main comes first, so a reader sees the big picture before the details. The parameter names in the prototype are optional (int add(int, int);), but they make it easier to read.

What happens without a declaration

If you call a function the compiler has not seen, older C guessed that it returns int. Since C99 this "implicit declaration" is an error or a warning, because the guess was often wrong and caused hard-to-find bugs. The message looks like call to undeclared function 'add'. The fix is to add the prototype, or move the function above the call.

Prototypes in header files

Declarations are also how C programs are split across files. The prototypes go into a header file (.h), which other files include; the definitions go into a .c file. That is exactly what #include <stdio.h> does: stdio.h contains the prototype of printf, whose definition is in the C library. The Header Files topic shows how to do this for your own functions.

Declarations must match

The declaration and the definition must agree on the return type and the parameter types. If they disagree, the compiler reports conflicting types. Keeping prototypes in one header that both the caller and the definition include makes such mistakes impossible.

Practice exercises

  1. Rewrite a program with three functions so that main comes first and the functions follow, using prototypes.
  2. Remove one prototype and read the error message.
  3. Change the parameter type in a definition but not in its prototype, and read the conflicting types error.