Defining and calling C functions, with parameters and return values explained visually.
int add(int a, int b) { return a + b; }return yields a valuevoid return and parametersf(x) = 2x + 1 from middle school or high school math?f(3) → substitute 3 for x → 7f(10) → substitute 10 for x → 21
// Math: f(x) = 2x + 1 int f(int x) { return 2 * x + 1; } int main(void) { printf("%d\n", f(3)); // -> 7 printf("%d\n", f(10)); // -> 21 return 0; }
f(x) is a function, and so is the C int f(int x). The call syntax (f(3)) and the meaning ("plug 3 in for x") are identical.| Math term | C term | Example |
|---|---|---|
| function name | function name | f, add, sqrt |
| input / independent variable | argument / parameter | x in f(x) |
| function value / dependent variable | return value | 7 in f(3) = 7 |
| definition | function body | { return 2*x + 1; } |
| substitution | passing an argument | f(3) = "let x=3, then compute" |
// Math: g(x, y) = x + y int add(int a, int b) { return a + b; } // add(3, 5) is just g(3, 5) β returns 8
intaddgint a, int breturn a+b;f(x) = 2x + 1 works whether x is an integer or a real number. In C, you declare the type of every input and output.int f(int x) means "takes an int, returns an int." For decimal values, you'd write double f(double x) as a separate function.
void hello(void) { // no return (void) printf("Hello!\n"); // side effect: output to screen }
void means "this function returns no value" β a concept with no direct equivalent in math.
f(3) is always 7. A C function, however, can return a different value each time it's called:
int r = rand(); // random number (different each call) int n = getchar(); // user keyboard input time_t t = time(NULL); // current clock timeThese all depend on external state (the random seed, stdin, or the system clock).
void change(int x) { x = 100; } // sets local x to 100 int main(void) { int a = 5; change(a); printf("%d\n", a); // -> 5 (unchanged!) }To actually modify the caller's variable, you need pointers (covered in a later lesson).
int get_year(void) { // void = no parameters return 2026; }They're useful for fetching external data or returning a fixed value.
| Name | Scope | Value |
|---|
max as minsum3(a, b, c)doubleCheck your understanding of this lesson!
void mean?void means "empty" — the function returns no value, so the return statement can be omitted.
Variables declared in the function definition are called "parameters." The values passed at the call site are called "arguments."
Variables declared inside a function are "local" β they only exist within that function.