Trace fact(4) for long fact(int n) { if (n == 0) return 1; return n * fact(n - 1); }. How many calls are made, what is the maximum stack depth, and what is returned?
A function is a named, reusable block of code with parameters and a return value. C passes every argument by value, simulates call by reference with pointers, and runs recursion on the call stack — plus command-line arguments, variadic functions and function pointers.
int max(int, int); declares the return and parameter types before use; the definition supplies the body. C99 requires a declaration before every call.swap(&a, &b)) simulates call by reference.main(int argc, char *argv[]): argc counts the program name too, argv[0] is the program name and argv[argc] is NULL.int (*fp)(int, int) is a pointer to a function; int *fp(int, int) is a function returning int *. qsort calls a comparator callback.A function is a self-contained block of statements that performs one task and can be called from elsewhere. Functions let you split a large problem into small, testable pieces (modular programming), avoid repeating code, and hide details behind a meaningful name. Every C program is a collection of one or more functions and must contain exactly one main, where execution starts.
#include <stdio.h>
int max(int a, int b); /* prototype (declaration) */
int main(void)
{
int x = 7, y = 12;
int m = max(x, y); /* call: x and y are the ARGUMENTS */
printf("max = %d\n", m); /* max = 12 */
return 0;
}
int max(int a, int b) /* definition: a and b are PARAMETERS */
{ /* return type int, function name max */
if (a > b)
return a; /* return ends the function at once */
return b;
}| Term | Meaning | In the example |
|---|---|---|
| Return type | type of the value sent back; void if nothing is returned | int |
| Formal parameters | variables in the definition's header that receive the values | a, b |
| Actual arguments | expressions supplied at the call | x, y |
| Prototype | declaration of return type, name and parameter types, ending in ; | int max(int a, int b); |
| Library function | ready-made function from the standard library | printf, declared in <stdio.h> |
| User-defined function | written by the programmer | max |
return expr; evaluates the expression, converts it to the return type and ends the function immediately. A function can return only one value this way (a KPSC question); to hand back several results, return a structure or write through pointer parameters. A void function may use a bare return; or just reach its closing brace. Falling off the end of a non-void function and using the result is undefined — except in main, where reaching the final } acts as return 0; (C99).
The compiler reads a file from top to bottom, so it must know a function's interface before its first call. A prototype supplies that interface: return type, name and parameter types (parameter names are optional, so int max(int, int); is enough). With a prototype in view, the compiler checks the number and types of the arguments and converts them where needed — max(3.9, 2) passes the int 3.
int f(void); declares a function with no parameters. Before C23, int f(); meant 'parameters unspecified', which disables argument checking; C23 makes empty brackets mean (void).Header files (.h) collect prototypes, macros and type definitions so that many source files can share them. #include <stdio.h> brings in the standard library's declarations, while your own headers are included with quotes: #include "geometry.h". A header should hold declarations; each function's definition lives in exactly one .c file, which is compiled and then linked with the rest.
/* ---------- geometry.h ---------- */
#ifndef GEOMETRY_H
#define GEOMETRY_H
double area(double r); /* prototypes only */
double circumference(double r);
#endif
/* ---------- geometry.c ---------- */
#include "geometry.h"
#define PI 3.14159265
double area(double r) { return PI * r * r; }
double circumference(double r) { return 2 * PI * r; }
/* ---------- main.c ---------- */
#include <stdio.h>
#include "geometry.h"
int main(void)
{
printf("%.2f\n", area(2.0)); /* 12.57 */
return 0;
}C passes every argument by value: each parameter is a fresh local variable initialised with a copy of the argument. Whatever the function does to its parameter, the caller's variable stays the same. That is why the first swap below fails.
#include <stdio.h>
void swap_value(int a, int b) /* receives copies */
{
int t = a; a = b; b = t; /* swaps the copies only */
}
void swap_pointer(int *a, int *b) /* receives ADDRESSES (copied by value) */
{
int t = *a; *a = *b; *b = t; /* changes the caller's variables */
}
int main(void)
{
int x = 1, y = 2;
swap_value(x, y);
printf("%d %d\n", x, y); /* 1 2 : unchanged */
swap_pointer(&x, &y);
printf("%d %d\n", x, y); /* 2 1 : swapped */
return 0;
}To let a function change a caller's variable, pass the variable's address and let the function work through the pointer. Strictly this is still call by value — the pointer is copied — but the copy points at the original object, so the effect is that of call by reference. C++ adds true reference parameters (void swap(int &a, int &b)); C has none.
f(x + 1)&x*p changes the caller's variableconst T * when the function must not modify itvoid clear(int a[], int n) can modify the caller's array, and sizeof(a) inside it gives the size of a pointer (8 bytes on 64-bit), not of the array — always pass the length separately. Structures, by contrast, are copied when passed by value.Pointer parameters are also how a C function returns several results: void divide(int a, int b, int *q, int *r) { *q = a / b; *r = a % b; } called as divide(17, 5, &q, &r) leaves q = 3 and r = 2. scanf uses exactly this idea, which is why its arguments need &.
Every call pushes an activation record (stack frame) onto the call stack. It holds the parameter copies, the return address — where to continue in the caller — saved registers and the function's auto variables. On return the frame is popped and its memory is reused by the next call. This last-in, first-out discipline is exactly a stack, which is why the stack is the data structure that implements function calls and recursion.
Because every call has its own frame, the calls of a recursive function do not interfere: fact(3), fact(2) and fact(1) each have a private n. The price is memory — every pending call holds a frame — and the stack is small (often 8 MB on Linux, 1 MB by default on Windows). Recursion that is too deep, or that never reaches its base case, ends in a stack overflow, usually a crash such as 'segmentation fault'.
A function is recursive if it calls itself — directly (f calls f) or indirectly (f calls g, which calls f). Every correct recursive function has two parts: a base case, answered without further recursion, and a recursive case, which reduces the problem to a smaller instance of itself and so moves toward the base case.
#include <stdio.h>
long fact(int n) /* n! = n × (n−1)!, with 0! = 1 */
{
if (n == 0) return 1; /* base case */
return n * fact(n - 1); /* recursive case */
}
int fib(int n) /* 0 1 1 2 3 5 8 13 ... */
{
if (n <= 1) return n; /* fib(0) = 0, fib(1) = 1 */
return fib(n - 1) + fib(n - 2);
}
int gcd(int a, int b) /* Euclid: gcd(a, b) = gcd(b, a % b) */
{
if (b == 0) return a;
return gcd(b, a % b);
}
int digit_sum(int n) /* digit_sum(1234) = 4 + digit_sum(123) */
{
if (n == 0) return 0;
return n % 10 + digit_sum(n / 10);
}
int main(void)
{
printf("%ld %d %d %d\n", fact(5), fib(7), gcd(84, 36), digit_sum(1234));
/* 120 13 12 10 */
return 0;
}| Function | Calls made for input n | Time | Stack depth |
|---|---|---|---|
fact(n) | n + 1 | O(n) | O(n) |
fib(n), naive | 2·F(n + 1) − 1 (15 calls for n = 5) | exponential, about 1.618ⁿ | O(n) |
gcd(a, b) | small: at most about 5 × the digits of the smaller number | O(log min(a, b)) | O(log min(a, b)) |
digit_sum(n) | number of digits + 1 | O(log n) | O(log n) |
When the recursive call is the very last action of the function, as in gcd, it is called tail recursion, and compilers can turn it into a loop that uses no extra stack. fact is not tail-recursive, because the multiplication happens after the inner call returns. Output order is a favourite question: printing before the recursive call gives n, n − 1, …, 1, while printing after it gives 1, 2, …, n, because those prints happen as the stack unwinds.
fact(-1) with the code above never reaches n == 0 and crashes; a robust version tests n <= 0. Large inputs can also overflow the result type: 21! no longer fits in a 64-bit long.The puzzle, popularised by Édouard Lucas in 1883, has three pegs and n discs of different sizes stacked on peg A, largest at the bottom. All discs must move to peg C, one at a time, never placing a larger disc on a smaller one. The recursive insight: to move n discs from A to C, first move the top n − 1 discs out of the way onto B, then move the largest disc to C, then move the n − 1 discs from B on top of it.
#include <stdio.h>
int moves = 0;
void hanoi(int n, char from, char to, char via)
{
if (n == 0) return; /* nothing to move */
hanoi(n - 1, from, via, to); /* park the top n-1 discs on via */
printf("%c->%c ", from, to); /* move the largest disc */
moves++;
hanoi(n - 1, via, to, from); /* bring the n-1 discs on top */
}
int main(void)
{
hanoi(3, 'A', 'C', 'B');
printf("\nmoves = %d\n", moves);
/* A->C A->B C->B A->C B->A B->C A->C
moves = 7 */
return 0;
}n == 0 base case used above). With 64 discs at one move per second, the job would take about 585 billion years.long fact_iter(int n)
{
long f = 1;
for (int i = 2; i <= n; i++)
f *= i;
return f;
}
int fib_iter(int n) /* O(n) time instead of exponential */
{
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
int t = a + b;
a = b;
b = t;
}
return a; /* fib_iter(7) = 13 */
}Any recursive algorithm can be rewritten iteratively — if necessary by managing an explicit stack yourself, which is exactly what the call stack does for you. Prefer recursion when it makes the solution clearly simpler (tree and graph algorithms, quicksort, mergesort) and the depth stays modest; prefer iteration for simple counting loops and for very deep or performance-critical work.
main may be written int main(void) or int main(int argc, char *argv[]). argc (argument count) is the number of words on the command line including the program name; argv (argument vector) is an array of strings in which argv[0] is the program name, argv[1] … argv[argc - 1] are the arguments, and argv[argc] is a NULL pointer. Arguments arrive as strings, so convert numbers with atoi or strtol. main's return value is the exit status: 0 or EXIT_SUCCESS means success.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
for (int i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);
if (argc == 3)
printf("twice the number: %d\n", 2 * atoi(argv[2]));
return 0;
}
/* $ ./a.out hello 42
argc = 3
argv[0] = ./a.out
argv[1] = hello
argv[2] = 42
twice the number: 84 */A variadic function takes a variable number of arguments, as printf does. Its prototype ends with ... after at least one named parameter, and the body reads the extra arguments with the macros of <stdarg.h>: va_list (the cursor type), va_start (begin after the last named parameter), va_arg(ap, type) (fetch the next argument as the given type) and va_end (finish). The function must learn how many arguments there are some other way — a count, a format string or a sentinel value.
#include <stdio.h>
#include <stdarg.h>
int sum_all(int count, ...)
{
va_list ap;
int total = 0;
va_start(ap, count); /* start after the last named parameter */
for (int i = 0; i < count; i++)
total += va_arg(ap, int); /* fetch the next int */
va_end(ap);
return total;
}
int main(void)
{
printf("%d\n", sum_all(4, 10, 20, 30, 40)); /* 100 */
return 0;
}inline (C99) suggests that the compiler replace each call with the function's body to save call overhead — the effect of a macro, but with type checking and with each argument evaluated exactly once. It is only a hint; short, frequently called helpers are typical candidates, usually written as static inline functions in headers.
A function's name used without brackets is its address. A pointer to a function stores such an address: int (*op)(int, int); declares op as a pointer to a function taking two ints and returning int. The brackets around *op are essential — int *op(int, int); declares a function returning int *. After op = add; both op(2, 3) and (*op)(2, 3) call add. Function pointers make callbacks possible (handing behaviour to another function), along with dispatch tables and plug-in designs.
#include <stdio.h>
#include <stdlib.h>
int ascending(const void *p, const void *q) /* qsort's contract: return */
{ /* <0, 0 or >0, like strcmp */
int a = *(const int *)p, b = *(const int *)q;
return (a > b) - (a < b); /* avoids overflow of a - b */
}
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int main(void)
{
int v[] = {42, 7, 19, 3, 25};
qsort(v, 5, sizeof v[0], ascending); /* qsort calls ascending back */
for (int i = 0; i < 5; i++) printf("%d ", v[i]); /* 3 7 19 25 42 */
int (*ops[3])(int, int) = {add, sub, mul}; /* array of function pointers */
printf("\n%d %d\n", ops[2](6, 7), (*ops[1])(6, 7)); /* 42 -1 */
return 0;
}Try the problem first, then reveal the working one step at a time.
Trace fact(4) for long fact(int n) { if (n == 0) return 1; return n * fact(n - 1); }. How many calls are made, what is the maximum stack depth, and what is returned?
List the moves made by hanoi(3, 'A', 'C', 'B') (move from A to C using B) and confirm the count with the recurrence.
With int func1(int k) { k++; return k; }, what does int k = 35; k = func1(k = func1(k = func1(k))); printf("k=%d", k); print?
For int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }, find fib(5) and the total number of calls that fib(5) makes.
Trace int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } for gcd(48, 18). How many calls are made?
Predict the output of void q(int n) { if (n == 0) return; printf("%d ", n); q(n - 1); printf("%d ", n); } for q(3).
A program is run as ./calc add 10 20. Give argc, argv[0], argv[2] and argv[4], and write the expression that adds the two numbers.
Declare (a) a pointer pf to a function that takes a double and returns int; (b) an array table of 4 pointers to functions taking (int, int) and returning int; (c) a function getop that takes a char and returns a pointer to a function taking (int, int) and returning int. Then call the function stored in table[1] with 8 and 2.
Tower of Hanoi: (a) how many moves do 6 discs need? (b) At one move per second, how long do 20 discs take? (c) How many times does the smallest disc move when n = 5?
int &x) do not exist in C.void f(int a[10]), sizeof(a) is the pointer size (8 on 64-bit). Pass the length separately.int *f(int); declares a function returning int *, while int (*f)(int); declares a pointer to a function — the brackets change everything../a.out x y gives argc = 3) and argv[argc] is NULL. The order in which arguments are evaluated is unspecified, and f(i++, i++) is undefined.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.
main() {
x = 5; y = 2; z = 10;
f(y, x, z);
print x; print y; print z;
}
f(p, q, r) {
q = q - 2;
r = p + q;
}