The Analogy: A Recipe Card, Not a Kitchen
A recipe card says what goes in, what comes out, and the steps between. It does not contain the ingredients themselves — you hand those over each time you cook, and the card works just as well for someone else's flour as for yours.
A C function is that card. Its prototype is the summary line at the top: what it takes and what it gives back. Its definition is the method. And crucially, when you call it, C makes a copy of every argument and hands the copy over. The function is cooking with its own flour, so anything it does to a parameter is invisible to the caller.
That copying rule is the single most important fact about C functions, and it is the source of most early confusion. If you want a function to change something the caller owns, you cannot pass the thing — you must pass its address. Everything in this lesson follows from that.
Syntax or Core Structure
A function has four parts: a return type, a name, a parameter list, and a body.
#include <stdio.h>
/* Declarations, also called prototypes: the shape, no body. */
double celsius_to_fahrenheit(double celsius);
int max_of(int a, int b);
void print_banner(void);
int main(void) {
print_banner();
printf("20C is %.1fF\n", celsius_to_fahrenheit(20.0));
printf("max(3, 9) is %d\n", max_of(3, 9));
return 0;
}
/* Definitions: the same shape, plus the method. */
double celsius_to_fahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32.0;
}
int max_of(int a, int b) {
return (a > b) ? a : b;
}
void print_banner(void) {
printf("--- conversions ---\n");
}
Output:
--- conversions ---
20C is 68.0F
max(3, 9) is 9
void in the return position means "hands nothing back". void in the parameter list means "takes nothing". They are unrelated uses of the same keyword.
The prototypes above main are what let main call functions defined further down the file. Without them the compiler reaches celsius_to_fahrenheit(20.0) having never heard the name, which in C99 and later is an error.
Technical Depth: Copies, Addresses and Linkage
Everything is passed by value
#include <stdio.h>
void try_to_double(int n) {
n = n * 2; /* doubles the copy */
printf("inside: n = %d\n", n);
}
void really_double(int *n) {
*n = *n * 2; /* doubles what the caller owns */
}
int main(void) {
int value = 21;
try_to_double(value);
printf("after try_to_double: %d\n", value);
really_double(&value);
printf("after really_double: %d\n", value);
return 0;
}
Output:
inside: n = 42
after try_to_double: 21
after really_double: 42
C has no reference parameters. really_double still receives a copy — a copy of the address — and that is enough, because both copies point at the same integer.
Arrays are the apparent exception, and they are not really an exception: an array argument decays to a pointer to its first element, so functions can always modify a caller's array. That also means sizeof inside the function measures a pointer, not the array, which is why every array parameter needs a length beside it.
Choosing a signature
| What the function needs to do | Signature | Called as |
|---|---|---|
| read one value | double f(double x) | f(3.0) |
| modify the caller's variable | void f(int *x) | f(&n) |
| read an array without changing it | long sum(const int *a, size_t n) | sum(arr, len) |
| return both a status and a value | int parse(const char *s, long *out) | if (parse(s, &v)) |
| fill a caller-owned buffer | void fmt(char *buf, size_t cap) | fmt(buf, sizeof buf) |
The fourth row is the workhorse convention of C: the return value reports success or failure, and the real result travels through a pointer. It exists because C has no exceptions and no tuples.
Two declaration details that matter
int f() and int f(void) are not the same in C. Empty parentheses historically mean "parameters unspecified", so f(1, 2, 3) compiles with no complaint whatsoever. Always write void explicitly.
Mark every function that is not part of your module's public interface as static. That gives it internal linkage, so the name cannot collide with an identically named helper in another source file, and the compiler can optimise it more aggressively.
Never return a pointer to a local
char *bad_greeting(void) {
char buffer[32] = "hello";
return buffer; /* buffer stops existing at the return */
}
The local array lives in the function's stack frame, which is reclaimed the moment the function returns. The pointer you get back aims at memory that now belongs to whatever runs next. The three legitimate alternatives are to have the caller supply the buffer, to return a pointer to a string literal or static object, or to malloc and document that the caller must free.
Real World Example: A Module in Three Files
This is how a C project is actually organised. The header states the contract, the source file implements it, and the caller includes only the header.
/* ---------- stats.h ---------- */
#ifndef STATS_H
#define STATS_H
#include <stddef.h>
/* Fills the out-parameters from n values.
Returns 1 on success, 0 if there is nothing to summarise.
Any out-parameter may be NULL if you do not want that figure. */
int stats_summary(const double *values, size_t n,
double *out_mean, double *out_min, double *out_max);
#endif /* STATS_H */
/* ---------- stats.c ---------- */
#include "stats.h"
int stats_summary(const double *values, size_t n,
double *out_mean, double *out_min, double *out_max) {
if (values == NULL || n == 0) {
return 0;
}
double sum = 0.0, lo = values[0], hi = values[0];
for (size_t i = 0; i < n; i++) {
sum += values[i];
if (values[i] < lo) { lo = values[i]; }
if (values[i] > hi) { hi = values[i]; }
}
if (out_mean != NULL) { *out_mean = sum / (double)n; }
if (out_min != NULL) { *out_min = lo; }
if (out_max != NULL) { *out_max = hi; }
return 1;
}
/* ---------- main.c ---------- */
#include <stdio.h>
#include "stats.h"
int main(void) {
double data[] = { 4.0, 8.0, 15.0, 16.0, 23.0, 42.0 };
size_t n = sizeof data / sizeof data[0];
double mean = 0.0, lo = 0.0, hi = 0.0;
if (!stats_summary(data, n, &mean, &lo, &hi)) {
fprintf(stderr, "no data\n");
return 1;
}
printf("n=%zu mean=%.2f min=%.1f max=%.1f\n", n, mean, lo, hi);
return 0;
}
gcc -std=c17 -Wall -Wextra -o app main.c stats.c
./app
Output:
n=6 mean=18.00 min=4.0 max=42.0
Several conventions are worth stealing wholesale. The include guard stops the header being pasted in twice. stats.c includes its own header, so a mismatch between promise and implementation is a compile error rather than a mystery at run time. const double *values documents that the input is read-only and lets the compiler enforce it. size_t is the correct type for a count. And sizeof data / sizeof data[0] computes the element count at the only place where data is still a real array rather than a decayed pointer.
Common Mistakes
- Calling a function the compiler has not seen. Put a prototype above
mainor in a header. In C99 and later an implicit declaration is an error, and in older compilers it silently assumedintand produced wrong results. - Writing
int f()for a function that takes nothing. Empty parentheses disable argument checking. Writeint f(void). - Expecting a function to change its argument.
swap(a, b)cannot work;swap(&a, &b)can. Everything is passed by value. - Returning a pointer to a local variable or local array. The memory is gone before the caller reads it, and the symptom appears far away from the cause.
- Falling off the end of a non-
voidfunction. If the caller uses the missing return value, that is undefined behaviour. Return explicitly on every path. - Declaring a prototype in one file and defining a different shape in another. The linker matches on the name alone, so this builds cleanly and corrupts at run time. Always share the prototype through a header.
- Using
sizeofon an array parameter. Inside the function it is a pointer, so you get 8, not the array's size. Pass the length as a separate parameter. - Leaving internal helpers non-
static. Two files with their ownstatic-lesshelper()produce a duplicate-symbol error at link time, or worse, silently share one.
Best Practices
- One job per function, named with a verb:
parse_line,compute_mean,write_report. - Put every public prototype in a header with an include guard, and have the implementing
.cfile include that same header. - Mark everything that is not public as
static. - Add
constto every pointer parameter you do not intend to modify. It documents intent and the compiler checks it. - Always spell out
(void)for an empty parameter list. - Pass a length beside every array or buffer pointer, and use
size_tfor it. - Adopt one error convention across the project — most C code returns a status and writes results through out-parameters — and never mix the two styles in one module.
- Keep parameter lists to about four items. Beyond that, group the related ones into a
structand pass a pointer to it.
Practice Exercises
- Extract three functions. Take a single
mainthat reads a radius, then prints the circumference and the area, and split it intoread_radius,circumferenceandarea, with prototypes abovemainand definitions below. The behaviour must be unchanged. - Swap, twice. Write
void swap(int *a, int *b)and prove it works. Then writevoid broken_swap(int a, int b), call it, print the caller's variables afterwards, and explain in a comment exactly what the function did swap. - A status-plus-out-parameter parser. Write
int parse_int(const char *text, long *out)that returns 1 only when the whole string is a valid number, usingstrtolwitherrnoand the end pointer. Test it with"42"," -7","12abc","abc",""and a value far larger thanLONG_MAX. - Build the module for real. Create
stats.h,stats.candmain.cas shown, and compile them in onegcccommand. Then change the parameter order in the header only, rebuild, and write down the exact error message and which stage of the build produced it.