Recursion in C is a function that calls itself on a smaller version of the problem until it reaches a base case it can answer directly. Every recursive function needs that base case plus a recursive step that moves toward it, and the depth must stay small enough for the stack.
#include <stdio.h>
unsigned long long factorial(unsigned int n)
{
if (n <= 1) /* base case: answer directly */
return 1;
return n * factorial(n - 1); /* recursive step: smaller input */
}
int main(void)
{
printf("%llu\n", factorial(5));
return 0;
}
Example output:
120
How a recursive call runs in C
Each call to factorial gets its own copy of n, its own return address and its own space for local variables. These live in a stack frame on the call stack. factorial(5) cannot return until factorial(4) returns, so five frames are alive at the deepest point:
factorial(5) waits for factorial(4)
factorial(4) waits for factorial(3)
factorial(3) waits for factorial(2)
factorial(2) waits for factorial(1)
factorial(1) returns 1 (base case)
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24
factorial(5) returns 5 * 24 = 120
The calls go down until the base case, then the results come back up. The stack frames are the memory cost of recursion, and that cost is what limits it. A loop that does the same work uses one frame no matter how many iterations it runs.
Recursion in C examples
These five functions show the patterns you will meet most often. All of them can be compiled as they are with any C compiler.
1. Greatest common divisor (Euclid's algorithm)
unsigned int gcd(unsigned int a, unsigned int b)
{
if (b == 0)
return a; /* base case */
return gcd(b, a % b); /* smaller second argument */
}
Tracing gcd(48, 18) by hand: 48 % 18 = 12, so the next call is gcd(18, 12). Then 18 % 12 = 6 gives gcd(12, 6), then 12 % 6 = 0 gives gcd(6, 0), which returns 6. The second argument is always smaller than before, so the base case is guaranteed to be reached. The depth is small even for large inputs, because the remainder shrinks quickly.
2. Sum of the digits of a number
unsigned int digit_sum(unsigned int n)
{
if (n < 10)
return n; /* base case: one digit */
return (n % 10) + digit_sum(n / 10); /* last digit + the rest */
}
digit_sum(1234) is 4 + digit_sum(123), which is 4 + 3 + digit_sum(12), and so on down to 1, giving 10. Integer division by 10 drops the last digit, which is what makes the input smaller.
3. Binary search on a sorted array
int binary_search(const int *items, int low, int high, int target)
{
if (low > high)
return -1; /* base case: not found */
int middle = low + (high - low) / 2; /* avoids overflow of low + high */
if (items[middle] == target)
return middle; /* base case: found */
if (items[middle] < target)
return binary_search(items, middle + 1, high, target);
return binary_search(items, low, middle - 1, target);
}
This one has two base cases and two recursive branches, but only one branch runs per call. Each call halves the range, so searching 1,000,000 elements needs at most about 20 levels (220 is 1,048,576). That is the kind of recursion that is safe on the stack: depth grows with log2 n, not with n.
4. Towers of Hanoi
#include <stdio.h>
void hanoi(int disks, char from, char to, char spare)
{
if (disks == 0)
return; /* base case: nothing to move */
hanoi(disks - 1, from, spare, to); /* park the smaller disks */
printf("Move disk %d from %c to %c\n", disks, from, to);
hanoi(disks - 1, spare, to, from); /* put them back on top */
}
Calling hanoi(3, 'A', 'C', 'B') prints 7 moves. Example output:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
The number of moves for n disks is 2n - 1, so 3 disks need 7 and 20 disks need 1,048,575. The stack depth is only n, though. Hanoi is slow because of the amount of work, not because of the depth.
5. Fibonacci, and why the obvious version is slow
unsigned long long fib(unsigned int n)
{
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}
This is correct, but it recomputes the same values again and again. fib(10) makes 177 function calls, and fib(30) makes 2,692,537, because the number of calls grows by a factor of about 1.6 with every step up in n. You can count them yourself by adding a global counter. For anything beyond n of about 40, use a loop:
unsigned long long fib_loop(unsigned int n)
{
unsigned long long previous = 0, current = 1;
for (unsigned int i = 0; i < n; i++) {
unsigned long long next = previous + current;
previous = current;
current = next;
}
return previous;
}
The loop makes n steps with no function-call overhead and no depth limit. If you need the recursive shape, store results in an array indexed by n (memoization) so that each value is computed once.
What happens when recursion never stops
A function with no reachable base case keeps pushing frames until the stack is full:
int broken(int n)
{
return broken(n - 1) + 1; /* no base case */
}
Unlike Python, C has no RecursionError and no configurable depth counter. The program simply runs out of stack memory and the operating system stops it. On Linux, the getrlimit(2) man page says of RLIMIT_STACK that "upon reaching this limit, a SIGSEGV signal is generated". Your shell then typically reports Segmentation fault. Other platforms report a stack overflow in their own way, so do not write code that depends on catching it.
A debugger shows a backtrace with the same function repeated thousands of times, which is the quickest way to confirm that recursion caused the crash. Reading that output is the same skill as in how to read a stack trace.
The usual causes:
- No base case, as above.
- A base case that is never reached.
factorialwith the testn == 0and a signed argument of -1 counts down forever. Usingn <= 1and an unsigned parameter, as in the first example, avoids that. - A step that does not shrink the input, such as calling
f(n)instead off(n - 1). - Large local variables. A function with a
char buffer[65536]uses 64 KiB of stack per call, so even a modest depth can exhaust the stack. - Correct recursion on deep input, such as a linked list with millions of nodes walked one node per call.
Integer overflow comes before stack overflow
Recursive math functions often fail on the number type before they fail on depth. factorial returns unsigned long long in the example above for that reason. 20! is 2,432,902,008,176,640,000, which fits in 64 bits. 21! is 51,090,942,171,709,440,000, which is larger than the maximum 64-bit unsigned value of 18,446,744,073,709,551,615, so the result wraps around to a wrong number. With a 32-bit int the same thing happens at 13!, which is 6,227,020,800. Check the range of your result type, not only the depth.
Does C optimize tail recursion?
A tail call is a recursive call that is the very last thing a function does, so the compiler could reuse the current frame. The C language does not require that. GCC documents -foptimize-sibling-calls as "Optimize sibling and tail recursive calls", enabled at -O2, -O3 and -Os. GCC's default level is -O0, so a plain gcc file.c does not enable it.
The gcd function above is tail-recursive, because its last action is the call to gcd. In the factorial function the call is not in tail position, since the result is still multiplied by n afterwards. A tail-recursive version carries the running product in an extra parameter:
unsigned long long factorial_tail(unsigned int n, unsigned long long product)
{
if (n <= 1)
return product;
return factorial_tail(n - 1, product * n); /* tail position */
}
/* call as factorial_tail(5, 1) */
Even so, whether the compiler turns this into a loop depends on the compiler and its flags, and a debug build will not. If your program must handle large depths, write the loop yourself.
Recursion or a loop in C?
| Recursion | Loop | |
|---|---|---|
| Fits naturally | Trees, binary search, divide-and-conquer, backtracking | Arrays, counters, anything linear |
| Stack use | One frame per active call | Constant |
| Failure mode | Crash when the stack is full | None from depth |
| Typical depth | Fine when it is log n or the nesting of the data | Not applicable |
A workable rule: if the depth is bounded by something small, like the height of a balanced tree or log2 of the input size, recursion is fine and often clearer. If the depth equals the number of elements, as with summing an array one item per call, use a loop.
Checklist for writing a recursive function in C
- Write the base case first. Decide which input you can answer immediately: 0, 1, an empty range, a NULL pointer.
- Assume the recursive call works on a smaller input, and work out how to build the answer from its result.
- Check that every path gets smaller, including negative numbers and empty input. Prefer unsigned parameters or an explicit guard.
- Estimate the maximum depth and the frame size. If the depth can reach tens of thousands, switch to a loop or an explicit stack you manage on the heap.
- Check the result type for overflow at the largest input you expect.
Frequently asked questions
- What is the base case in a recursive C function?
- The base case is the input for which the function returns a value directly, without calling itself. In a factorial function it is n <= 1, which returns 1. Every recursive path must move toward the base case, otherwise the calls never stop and the program runs out of stack.
- What happens if a recursive function in C never stops?
- Each call uses stack memory for its parameters, local variables and return address. When the stack reaches its limit, the program crashes. On Linux the limit is controlled by RLIMIT_STACK, and the man page says a SIGSEGV signal is generated on reaching it. C itself defines no error for this, so the exact crash message depends on the operating system.
- Does C optimize tail recursion?
- Not as a language rule. GCC documents -foptimize-sibling-calls, which optimizes sibling and tail recursive calls, as enabled at -O2, -O3 and -Os. GCC's default level is -O0, which does not enable it. Code that must handle large depths should be written as a loop rather than relying on the compiler.
- Is recursion or a loop better in C?
- Use a loop when the depth grows with the input size, for example summing an array one element at a time. Use recursion when the problem is naturally tree-shaped or divide-and-conquer, such as binary search, tree traversal or merge sort, where the depth stays small.