A function is a named block of code you can call many times. Functions split a program into small, testable pieces. This section covers declaring and defining functions, passing data by value and by reference (with pointers), working with arrays and variable arguments, scope and lifetime, the static and extern keywords, and recursion.
Static and extern live here.
Open "static and extern" for persistent local variables and file-private functions, and "Pass by reference" for the pointer technique that lets a function change its caller's variables.
Path
Learning Path
Work through the stages in order, or jump to a topic from the index below (17 tutorials).
A quick taste of functions. Compile with gcc file.c -std=c11 -Wall -o out.
Example 1 — Define and call a function
A prototype, a call from main, and the definition.
C
#include <stdio.h>
double average(int a, int b);
int main(void) {
printf("average = %.1f\n", average(7, 10));
return 0;
}
double average(int a, int b) {
return (a + b) / 2.0;
}
Output
average = 8.5
How It Works
The prototype tells the compiler the function's name, parameters, and return type.
main passes the arguments 7 and 10.
Dividing by 2.0 keeps the fractional part, so the result is 8.5.
Index
C Functions Topics
Every guide in this section with a one-line summary (17 tutorials).
Writing functions
6 tutorials
Declare, define, call, and return from your own functions.