Functions
Functions let you name a piece of logic, reuse it, and test it on its own. Even big C programs like the Linux kernel are just thousands of small functions calling each other.
Defining and calling
#include <stdio.h>
int square(int x) {
return x * x;
}
void greet(const char *name) {
printf("Hello, %s!\n", name);
}
int main(void) {
greet("Asha");
int s = square(12);
printf("12 squared is %d\n", s);
printf("square(square(3)) = %d\n", square(square(3)));
return 0;
}Hello, Asha! 12 squared is 144 square(square(3)) = 81
A function definition has a return type, a name, parameters with their types, and a body. void means "returns nothing". return ends the function and hands back the value.
Declare before use: prototypes
C reads a file from top to bottom, so a function must be declared before it's called. If you want main at the top, declare the other functions first with a prototype: the first line, ending in ;:
#include <stdio.h>
double average(const int values[], int count); // prototype
int main(void) {
int marks[] = {72, 88, 95, 61};
printf("average: %.2f\n", average(marks, 4));
return 0;
}
double average(const int values[], int count) { // definition
if (count == 0) return 0.0;
long sum = 0;
for (int i = 0; i < count; i++) sum += values[i];
return (double)sum / count;
}average: 79.00
Prototypes are what header files (.h) contain. #include <stdio.h> is mostly prototypes like int printf(const char *format, …);. You'll write your own in The preprocessor and multi-file programs.
Call a function with the wrong arguments and the compiler, thanks to the prototype, refuses:
#include <stdio.h>
int square(int x);
int main(void) {
printf("%d\n", square(2, 3));
return 0;
}
int square(int x) { return x * x; }main.c: In function ‘main’:
main.c:6:20: error: too many arguments to function ‘square’; expected 1, have 2
6 | printf("%d\n", square(2, 3));
| ^~~~~~ ~
main.c:3:5: note: declared here
3 | int square(int x);
| ^~~~~~Arguments are copied
C passes arguments by value: the function gets a copy, and changing it doesn't affect the caller's variable:
#include <stdio.h>
void try_to_reset(int n) {
n = 0;
printf("inside: n = %d\n", n);
}
void really_reset(int *n) {
*n = 0;
}
int main(void) {
int count = 42;
try_to_reset(count);
printf("after try_to_reset: %d\n", count);
really_reset(&count);
printf("after really_reset: %d\n", count);
return 0;
}inside: n = 0 after try_to_reset: 42 after really_reset: 0
To let a function change a variable, pass its address (&count) and have the function take a pointer (int *n). The Pointers lesson explains this properly; for now, recognise the pattern. It's also how functions "return" more than one value:
#include <stdio.h>
void min_max(const int a[], int n, int *min, int *max) {
*min = *max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *min) *min = a[i];
if (a[i] > *max) *max = a[i];
}
}
int main(void) {
int temps[] = {21, 34, 18, 29, 25};
int lo, hi;
min_max(temps, 5, &lo, &hi);
printf("min %d, max %d\n", lo, hi);
return 0;
}min 18, max 34
Arrays are the exception: they're never copied. The function receives the address of the first element, so it can change the caller's array. That's why average above marked its array const: a promise not to modify it, checked by the compiler.
Returning errors
C has no exceptions. Functions report failure through their return value: commonly 0 for success and non-zero (or -1) for an error, with the real result written through a pointer:
#include <stdio.h>
// Returns 0 on success, -1 if dividing by zero.
int safe_divide(int a, int b, int *result) {
if (b == 0) return -1;
*result = a / b;
return 0;
}
int main(void) {
int r;
if (safe_divide(10, 2, &r) == 0) printf("10 / 2 = %d\n", r);
if (safe_divide(10, 0, &r) != 0) printf("10 / 0: error, can't divide by zero\n");
return 0;
}10 / 2 = 5 10 / 0: error, can't divide by zero
Always check return values. Ignoring a failed fopen or malloc is one of the most common C bugs. You can make the compiler insist with C23's [[nodiscard]]:
#include <stdio.h>
[[nodiscard]] int save_file(const char *name) {
printf("saving %s\n", name);
return 0;
}
int main(void) {
save_file("report.txt");
return 0;
}main.c: In function ‘main’:
main.c:9:5: warning: ignoring return value of ‘save_file’, declared with attribute ‘nodiscard’ [-Wunused-result]
9 | save_file("report.txt");
| ^~~~~~~~~~~~~~~~~~~~~~~
main.c:3:19: note: declared here
3 | [[nodiscard]] int save_file(const char *name) {
| ^~~~~~~~~
saving report.txtScope and static
Variables declared inside a function (or any { } block) are local: they exist only while it runs, and every call gets fresh ones. A static local is the exception: it's created once and keeps its value between calls:
#include <stdio.h>
int next_id(void) {
static int id = 0; // initialised once, remembered between calls
id++;
return id;
}
int main(void) {
for (int i = 0; i < 3; i++) printf("id %d\n", next_id());
return 0;
}id 1 id 2 id 3
Variables declared outside all functions are global: visible everywhere in the file and alive for the whole program. Use them sparingly; they make code hard to follow and test. A static function or global is visible only inside its own file, which is C's way of making something private.
Recursion
A function can call itself. Each call gets its own copy of the local variables, on the stack:
#include <stdio.h>
unsigned long long factorial(unsigned n) {
if (n <= 1) return 1; // base case: stops the recursion
return n * factorial(n - 1);
}
int fib(int n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
int main(void) {
printf("10! = %llu\n", factorial(10));
printf("20! = %llu\n", factorial(20));
for (int i = 0; i < 10; i++) printf("%d ", fib(i));
printf("\n");
return 0;
}10! = 3628800 20! = 2432902008176640000 0 1 1 2 3 5 8 13 21 34
Every recursive function needs a base case. Without one, it calls itself until the stack (usually 8 MB) runs out and the program crashes with a segmentation fault. For deep or performance-critical work, a loop is usually better: this fib takes exponentially longer as n grows.
Useful standard functions
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
printf("sqrt(2) = %.4f\n", sqrt(2.0));
printf("pow(2, 10) = %.0f\n", pow(2, 10));
printf("round(2.5) = %.0f, floor(2.7) = %.0f, ceil(2.1) = %.0f\n", round(2.5), floor(2.7), ceil(2.1));
printf("abs(-7) = %d\n", abs(-7));
printf("atoi(\"123\") + 1 = %d\n", atoi("123") + 1);
return 0;
}gcc -std=c23 -Wall -Wextra -o main main.c -lmsqrt(2) = 1.4142
pow(2, 10) = 1024
round(2.5) = 3, floor(2.7) = 2, ceil(2.1) = 3
abs(-7) = 7
atoi("123") + 1 = 124The math functions live in a separate library on Linux: add -lm when you link. (atoi can't report errors; prefer strtol for real input.)
Practice
- Write
int is_prime(int n)and use it to print every prime below 50. - Write
void swap(int *a, int *b)that swaps two variables, and test it. - Write
int parse_age(const char *text, int *age)that returns0and sets*agefor valid input between 0 and 150, and-1otherwise (usestrtol). - Write a recursive
int power(int base, int exp).
1.Why do C files often start with prototypes like int square(int x);?
2.A function does n = 0; on its int n parameter. What happens to the caller's variable?
3.What does a static local variable do?
4.Why link with -lm?