C: Advanced Functions
Recursion is like two mirrors facing each other -- images nest within themselves until the distant point of light vanishes. A function that calls itself solves problems through this power of progressive reduction.
1. Recursion Principles
Recursion is a programming technique where a function calls itself directly or indirectly. Every recursion must have two elements:
- Recursive condition: the problem can be broken down into smaller subproblems of the same kind
- Base case (terminating condition): the smallest subproblem has a direct answer and no longer recurses
// Function definition
int factorial(int n) {
// Conditional check
if (n <= 1) {
// Return result
return 1;
}
// Return result
return n * factorial(n - 1);
}
Take factorial(4) as an example, the execution process:
factorial(4)
= 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * 2 * factorial(1)
= 4 * 3 * 2 * 1
= 24
2. Classic Recursion Examples
(1) Factorial
The definition of n factorial: n! = n x (n-1)!, and 0! = 1.
// Function definition
long factorial(int n) {
// Conditional check
if (n <= 1) return 1;
// Return result
return n * factorial(n - 1);
}
Note that the long type has a limited range; factorial(20) is already close to the 64-bit limit.
(2) Fibonacci Sequence
Fibonacci definition: F(1)=1, F(2)=1, F(n)=F(n-1)+F(n-2).
// Function definition
long fib(int n) {
// Conditional check
if (n <= 2) return 1;
// Return result
return fib(n - 1) + fib(n - 2);
}
fib(40) requires hundreds of millions of calls because many subproblems are recomputed. In practice, use a loop or memoization.
(3) Tower of Hanoi
Move n disks from peg A to peg C, using peg B as auxiliary. Rule: a larger disk cannot be placed on a smaller one.
// Preprocessor directive
#include <stdio.h>
// Function definition
void hanoi(int n, char from, char mid, char to) {
// Conditional check
if (n == 1) {
// I/O operation
printf("%c -> %c\n", from, to);
// Return result
return;
}
hanoi(n - 1, from, to, mid);
// I/O operation
printf("%c -> %c\n", from, to);
hanoi(n - 1, mid, from, to);
}
// Function definition
int main(void) {
hanoi(3, 'A', 'B', 'C');
// Return result
return 0;
}
A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C
The idea: first move the top n-1 disks to the auxiliary peg, move the largest disk to the target peg, then move the n-1 disks from the auxiliary peg to the target peg. 3 disks require 7 moves; n disks require 2^n - 1 moves.
▶ Example
Recursively compute the sum of an integer's digits:
▶ Try it Yourself15
7
digit_sum(12345) = 5 + digit_sum(1234) = 5 + 4 + digit_sum(123) = ... = 5+4+3+2+1 = 15.
3. Variable Scope
Scope determines which regions of code can see and use a variable.
(1) Block Scope
Variables defined within {} are only visible inside that block and are destroyed when the block ends:
// Function definition
int main(void) {
// Variable declaration
int x = 10;
{
// Variable declaration
int y = 20;
// I/O operation
printf("%d %d\n", x, y);
}
// I/O operation
printf("%d\n", x);
// Return result
return 0;
}
y exists only in the inner block and cannot be accessed from the outer block.
(2) File Scope
Variables defined outside all functions have file scope and are visible from their definition to the end of the file. These are called global variables:
// Variable declaration
int count = 0;
// Function definition
void increment(void) {
count++;
}
// Function definition
int main(void) {
increment();
increment();
// I/O operation
printf("%d\n", count);
// Return result
return 0;
}
(3) Name Shadowing
A variable in an inner scope shadows a variable with the same name in an outer scope:
// Variable declaration
int x = 100;
// Function definition
int main(void) {
// Variable declaration
int x = 10;
// I/O operation
printf("%d\n", x);
// Return result
return 0;
}
The output is 10; the inner x shadows the global x. The global x cannot be directly accessed inside the inner block.
4. Storage Classes
Storage classes determine a variable's lifetime and visibility. C has four storage class keywords: auto, static, extern, and register.
(1) auto
auto is the default storage class for local variables and is usually omitted. Variables are created when the block is entered and destroyed when the block is exited:
// Function definition
void func(void) {
auto int x = 10;
}
This is equivalent to int x = 10;.
(2) static
When static modifies a local variable, the variable exists for the entire program runtime, but its scope remains limited to the function. Key property: it is initialized only once, and subsequent calls retain the previous value.
// Preprocessor directive
#include <stdio.h>
// Function definition
void counter(void) {
static int count = 0;
count++;
// I/O operation
printf("Call #%d\n", count);
}
// Function definition
int main(void) {
counter();
counter();
counter();
// Return result
return 0;
}
Call #1
Call #2
Call #3
Without static, count would be reinitialized to 0 each time, always printing "Call #1".
When static modifies a global variable or function, it restricts its visibility to the current file (internal linkage); other source files cannot access it via extern.
(3) extern
extern declares a global variable defined in another source file, telling the compiler "this variable exists, but is not defined in the current file":
file1.c:
// Variable declaration
int shared_data = 42;
file2.c:
#include <stdio.h>
extern int shared_data;
int main(void) {
printf("%d\n", shared_data);
return 0;
}
extern does not allocate memory; it is only a declaration. Multi-file projects need extern to share global data.
(4) register
register suggests the compiler store the variable in a CPU register for faster access:
// Function definition
void fast_loop(void) {
register int i;
// For loop
for (i = 0; i < 1000000; i++) {
}
}
Modern compilers are very good at optimization and typically place frequently used variables in registers automatically, so the register hint has little effect. Note: you cannot take the address of a register variable (&), because registers do not have memory addresses.
▶ Example
Iterative Fibonacci using a loop (avoiding recursion's repeated computation):
▶ Try it YourselfF(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
This iterative version has O(n) time complexity, far better than the naive recursion's O(2^n).
▶ Example 3: Recursive Factorial
▶ Try it Yourself输出:
TEXT1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320
❓ FAQ
register has almost no additional effect; this keyword is primarily of historical significance.📖 Summary
- Recursion must include a base case, or the stack will overflow
- Naive recursive Fibonacci is inefficient; real problems need loops or memoization
- Local variables have block scope; global variables have file scope
- static local variables persist throughout the program, but their scope remains unchanged
- extern enables cross-file variable sharing; register has little significance in modern compilers
📝 Exercises
- Write a recursive function
void print_reverse(int n)that prints the digits of a positive integer in reverse order (e.g., 123 outputs 3 2 1). - Write a function that uses a static variable to count how many times it has been called. Call it 5 times in main, then print the count.
- Implement binary search recursively: search for a target value in a sorted array; return the index if found, or -1 if not found.