Interview Q&A · C · 10 questions in this topic
Functions & Recursion — C Interview Q&A
How C functions work — declarations, pass-by-value, recursion, and the stack-frame model behind call bugs. Part of Functions & Storage · 202 questions in the C bank.
How do function declaration, definition and calls fit together?
Answer
A declaration (prototype) gives the signature so callers compile; the definition provides the body exactly once; calls evaluate arguments and transfer control. Since C99, implicit declarations are illegal — every function must be declared before use, normally via a header.
Missing prototypes cause the classic implicit-int era bugs that -Wimplicit-function-declaration still hunts.
Example
/* mathutil.h: declaration */ int add(int a, int b); /* mathutil.c: definition */ int add(int a, int b) { return a + b; } /* main.c: caller includes mathutil.h */
💡 Declare in headers, define once, include before use — the complete function hygiene rule.
Does C have pass-by-reference?
Answer
No — C is strictly pass-by-value: every argument is copied. Reference-like behavior is simulated by passing pointers, letting the callee mutate through them. That is why scanf takes &x and why swap needs int*.
The discipline: pass small values directly, large read-only data as const pointers, and out-params as pointers with documented ownership.
Example
void swap(int *a, int *b) { /* simulated by-reference via pointers */ int t = *a; *a = *b; *b = t; } void read_only(const int *p, size_t n); /* no copy, no mutation */
💡 No references, only values and pointers is the one-line C parameter model.
What is recursion, and what must every recursive C function have?
Answer
Recursion is a function calling itself on a smaller subproblem. Every correct recursion needs a base case that terminates and a progress guarantee toward it. Missing either gives infinite recursion and stack overflow.
C adds practical concerns: deep recursion exhausts the fixed call stack (prefer iteration for huge n), and naive exponential recursion (textbook Fibonacci) needs memoization or DP.
Example
long long fact(int n) { if (n <= 1) return 1; /* base case */ return (long long)n * fact(n - 1); /* progress: n shrinks */ }
💡 Always say base case plus progress in one breath — interviewers listen for both halves.
What happens at runtime when a function is called (stack frames)?
Answer
The caller evaluates arguments, then the call sequence pushes the return address and creates a frame: saved registers, locals, and temporaries. Control jumps to the callee, which tears the frame down on return and hands a value back (often in a register). Too many nested frames exhaust the stack.
This model explains why locals die at scope exit, why returning a pointer to a local dangles, and why deep recursion crashes with stack overflow.
Key points
- 1Call — arguments evaluated, return address saved, frame created.
- 2Execute — locals live in the frame; scope exit destroys them.
- 3Return — frame destroyed; results come back by value or pointer.
💡 Tie the frame model to the dangling-local bug — abstract stack talk becomes a bug you can explain.
What is the difference between `int main()` and `int main(void)` in C?
Answer
In C (unlike C++), int main() declares a function taking an unspecified number of arguments — it disables arity checking. int main(void) explicitly takes no arguments and is the correct hosted signature.
Empty parens are a leftover from pre-prototype C; modern style always writes (void) for zero parameters.
Example
int f(void); /* zero args, checked */ /* int g(); // unknown args, unchecked — avoid in modern C */
What are variadic functions (`printf`-style) and how do they work?
Answer
Variadic functions take a variable argument count via ... plus <stdarg.h>: va_list holds the traversal state, va_start binds it to the last fixed parameter, va_arg pulls each argument with an explicit type, va_end cleans up. Type safety is entirely on you — mismatched va_arg types are undefined behavior.
Always pass an explicit count or format string so the callee knows when to stop; there is no built-in terminator.
Example
#include <stdarg.h> int sum(int n, ...) { va_list ap; va_start(ap, n); int total = 0; for (int i = 0; i < n; i++) total += va_arg(ap, int); va_end(ap); return total; }
What is the difference between `static` functions and `extern` functions?
Answer
extern (the default) gives external linkage: the function is visible to the whole program and callable from other translation units via a prototype. static restricts to internal linkage: the function is private to its .c file, enabling same-named helpers across files and better optimization.
Default to static for helpers; expose only the module API as extern through the header.
Example
/* sensor.c */ static int calibrate(void) { return 42; } /* file-private */ int read_sensor(void) { return calibrate(); } /* module API */
💡 Static-by-default for helpers is the modular-C habit interviewers want to hear.
What is the difference between `inline` in C99 vs C++?
Answer
C99 inline is a linkage dance, not just a hint: a bare `inline` definition does not emit an externally-visible symbol (it is for inlining into the same TU only), while `extern inline` emits exactly one external definition. The safe pattern is `static inline` in headers — internal linkage per TU, no linker conflicts.
Unlike C++, C inline never implies internal linkage by itself, which is why the header pattern differs between the languages.
Example
/* util.h: safe C header pattern */ static inline int square(int x) { return x * x; }
💡 static inline in headers is the portable C answer; the extern-inline dance is the depth follow-up.
How do `argc` and `argv` work, and what are the pitfalls?
Answer
argv[0] is the program name (or empty), not the first real argument — real arguments start at argv[1]. argv[argc] is NULL. Arguments arrive as text, so numbers need strtol/strtod with error handling, and the count must be validated before indexing.
Never assume a minimum argc: check it, print usage, and exit with EXIT_FAILURE.
Example
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc < 2) { printf("usage: %s <n>\n", argv[0]); return EXIT_FAILURE; } char *end = NULL; long n = strtol(argv[1], &end, 10); /* validated parse, not atoi */ return 0; }
💡 strtol with end-pointer checking beats atoi — atoi cannot report errors at all.
How do you return multiple values or an array from a C function?
Answer
Functions return one value; the rest travels through out-parameters (caller-provided pointers), a returned struct (copied by value — fine when small), or a heap buffer whose ownership transfers to the caller with documented free responsibility.
Never return pointers to locals. For arrays, either the caller allocates (safest: pass buffer plus size) or the callee mallocs and documents that the caller must free.
Example
/* caller-provided buffer: safest pattern */ int parse(const char *s, int *out, size_t cap); /* callee-allocated: documents transfer */ /* char *dup = malloc(...); return dup; // caller must free */
Recommended resourcesAffiliate links · may earn us a commission