Coding Techniques
Functions · Study material
Memoization with a static array
Naive recursive Fibonacci recomputes the same values exponentially many times. Caching each result in a static array makes it O(n).
#include <stdio.h>
unsigned long long fib(int n) {
static unsigned long long memo[94]; /* fib(93) is the largest that fits in 64 bits */
if (n < 2)
return (unsigned long long) n;
if (memo[n] == 0)
memo[n] = fib(n - 1) + fib(n - 2); /* each value is computed once */
return memo[n];
}
int main(void) {
printf("fib(10) = %llu\nfib(90) = %llu\n", fib(10), fib(90));
return 0;
}
fib(10) = 55 fib(90) = 2880067194370816120
Turning recursion into a loop
When the recursive call is the last thing a function does (a tail call), the same logic fits in a loop that uses no extra stack.
#include <stdio.h>
int gcd_rec(int a, int b) { return b == 0 ? a : gcd_rec(b, a % b); } /* tail call */
int gcd_loop(int a, int b) { /* same logic, no stack growth */
while (b != 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
int main(void) {
printf("%d %d\n", gcd_rec(84, 36), gcd_loop(84, 36));
return 0;
}
12 12
Returning several values in a struct
A function can return a whole struct by value – often cleaner than three output pointers.
#include <stdio.h>
struct stats {
int min, max;
double mean;
};
struct stats describe(const int *a, int n) { /* several results in one return value */
struct stats s = {a[0], a[0], 0.0};
long sum = 0;
for (int i = 0; i < n; i++) {
if (a[i] < s.min) s.min = a[i];
if (a[i] > s.max) s.max = a[i];
sum += a[i];
}
s.mean = (double) sum / n;
return s;
}
int main(void) {
int a[] = {4, 8, 15, 16, 23, 42};
struct stats s = describe(a, 6);
printf("min %d, max %d, mean %.2f\n", s.min, s.max, s.mean);
return 0;
}
min 4, max 42, mean 18.00
Status return + output parameter
For operations that can fail, return a status and write the result through a pointer. Mark the status [[nodiscard]] in C23 so callers cannot silently ignore it.
[[nodiscard]] bool parse_age(const char *text, int *age); /* C23 */
int age;
if (!parse_age(input, &age)) {
puts("Please enter a valid age.");
} Good function habits
- One job per function, with a name that says what it returns or does.
- Prototype every function; write
(void)for no parameters. - Mark helper functions
staticso they stay private to the file. - Use
constfor pointer parameters the function only reads. - Never depend on the evaluation order of arguments:
f(i++, i)is a bug. - Compile with
-Wall -Wextra: missing returns and implicit declarations are caught at once.