🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Tracing Recursive Output in C
Chapter 6, Functions: learn the method for tracing recursive functions in C, including print order, the decrement operator trap, mutual recursion, the comma operator and name shadowing. A free C tutorial for embedded learners.
Predicting what a program prints is the most common question in C exams and interviews, and nothing tests it harder than tracing recursive functions in C. A tiny change, such as moving one printf above or below the recursive call, reverses the whole output. A single --x inside an argument changes what the function prints on the way back. This lecture of our free C programming course gives you a reliable method for tracing recursive functions in C and applies it to five patterns that appear again and again: print order, decrement side effects, mutual recursion, the comma operator and shadowed variable names.
What You Will Learn
- Why printing before the recursive call counts down while printing after it counts up.
- How an argument such as
--xmodifies the caller’s own copy of the variable. - How two functions can call each other, and why a forward declaration is needed.
- What the comma operator returns and why compilers warn about it.
- Which variable wins when a local and a global share a name.
- A repeatable five-step routine for tracing recursive functions in C on paper.
Prerequisites
Read the earlier lectures on function calls, the stack and basic recursion. You also need to know the pre-decrement and post-decrement operators from the Operators chapter. Every program compiles cleanly with gcc -std=c11 -Wall -Wextra.
Tracing Recursive Functions in C: Print Before or After the Call
Every recursive function has a going-down phase, while calls pile up, and a coming-back phase, while they return. Anything placed before the recursive call runs on the way down; anything placed after it runs on the way back. The three functions below differ only in where the printf sits and in how the argument is changed.
#include <stdio.h>
void print_then_recurse(int x)
{
printf("%d ", x);
if (x > 2)
print_then_recurse(x - 1);
}
void recurse_then_print(int x)
{
if (x > 2)
recurse_then_print(x - 1);
printf("%d ", x);
}
/* The argument --x also changes this frame's own copy of x. */
void unwind_with_decrement(int x)
{
if (x > 2)
unwind_with_decrement(--x);
printf("%d ", x);
}
int main(void)
{
print_then_recurse(6); printf("\n");
recurse_then_print(6); printf("\n");
unwind_with_decrement(6); printf("\n");
return 0;
}
6 5 4 3 2
2 3 4 5 6
2 2 3 4 5
The first line counts down because each frame prints its value before diving deeper. The second line counts up because the deepest frame prints first and the shallowest prints last, so the order of printing is the reverse of the order of calling. The third line is the interesting one, and the next section explains it.
Same calls, opposite print order
A five-step tracing routine
- Write the function call with its real argument at the top of a page.
- Under it, write one line per frame, noting the parameter value when the frame starts.
- Mark where the base case stops the descent.
- Note which statements run before the recursive call and which run after it.
- Replay the page from the deepest frame upward, performing the statements that come after the call.
The Decrement Trap When Tracing Recursive Functions in C
The third function passes --x to the next call, then prints x after returning. Pre-decrement does two jobs at once: it lowers the caller’s x and hands the lowered value to the callee. When control returns, the caller’s x is already smaller, so what it prints is not the value it started with. Compare the frames in a table.
| Frame starts with | x after --x | Passed to next call | Prints on return |
|---|---|---|---|
| 6 | 5 | 5 | 5 |
| 5 | 4 | 4 | 4 |
| 4 | 3 | 3 | 3 |
| 3 | 2 | 2 | 2 |
| 2 (base case) | unchanged | no call | 2 |
Reading the last column from the bottom up gives 2, 2, 3, 4, 5, which matches the program. The value 2 appears twice: once from the base-case frame and once from the frame that started with 3 and decremented to 2. The number 6 is never printed at all.
x - 1 over --x inside a call. It passes the smaller value without altering the caller’s variable, so the code prints what you expect and is easier to trace. Several coding standards ban side effects in arguments for exactly this reason.
Mutual Recursion When Tracing Recursive Functions in C
Direct recursion means a function calls itself. Indirect or mutual recursion means function A calls B and B calls A. Because the compiler reads a file from top to bottom, the first function needs to know the second one exists, so a forward declaration, also called a prototype, appears before both definitions.
#include <stdio.h>
void pulse_high(int n); /* forward declaration, needed for the cycle */
void pulse_low(int n);
void pulse_high(int n)
{
if (n < 0)
return;
printf("high %d\n", n);
pulse_low(n - 1);
}
void pulse_low(int n)
{
if (n < 0)
return;
printf("low %d\n", n);
pulse_high(n - 1);
}
int main(void)
{
pulse_high(5);
return 0;
}
high 5
low 4
high 3
low 2
high 1
low 0
The two functions take turns, and the argument shrinks by one each time, so after six steps it falls below zero and both functions return. Indirect recursion appears in real systems more often than people expect, for example in a recursive-descent parser where an expression handler calls a term handler, which in turn calls the expression handler for bracketed input.
Mutual recursion between two pulse functions
pulse_high(5)
Prints high 5, then calls pulse_low with 4.
pulse_low(4)
Prints low 4, then calls pulse_high with 3.
Down to below zero
The chain alternates until the argument goes negative, then all frames return.
Comma Operator and Name Shadowing in Recursive Programs
Two more details decide many output questions even though they are not recursion themselves. First, the comma operator evaluates its left operand, throws the value away, and yields the right operand. So return (a, b, c); returns c. Compilers warn about it, because the first two values usually mean a typo. With GCC and -Wall -Wextra you will see “left-hand operand of comma expression has no effect”. The commas that separate function arguments are not comma operators at all.
Second, when a local variable has the same name as a global one, the local hides the global inside its block. The program below shows both rules.
#include <stdio.h>
int level = 5; /* global */
int read_level(void)
{
int level = 2; /* local name hides the global */
return level;
}
int last_of_three(int a, int b, int c)
{
(void)a;
(void)b;
return c; /* what (a, b, c) would also give */
}
int main(void)
{
int x, y;
int v = (x = 3, y = 4, x + y); /* comma operator: left to right */
printf("%d %d\n", read_level(), level);
printf("v = %d, last = %d\n", v, last_of_three(1, 2, 3));
return 0;
}
2 5
v = 7, last = 3
The first line prints 2 and 5: the function sees its own level, while main sees the global. The second line shows a comma expression with real side effects: x becomes 3, then y becomes 4, then x + y gives 7, which is stored in v.
| Expression | Value | Reason |
|---|---|---|
(1, 2, 3) | 3 | The rightmost operand wins |
v = (x = 3, y = 4, x + y) | 7 | Left to right, last value kept |
v = x = 3, y = 4 | v becomes 3 | Assignment binds tighter than the comma |
Local level inside the function | local copy | Inner scope hides outer scope |
Real-World Use Cases
- Reverse printing: print-after-recursion is the classic trick for emitting the digits of a number from the most significant end.
- Parsers and state machines: mutual recursion models grammars where rules refer to each other.
- Debugging legacy code: old firmware often hides side effects in arguments. Knowing the decrement trap lets you find them fast.
- Code reviews: shadowed names are a classic source of “my global never changes” bugs.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
| Reading the output in call order when the print follows the call | Your trace is reversed | Mark statements before and after the recursive call |
Forgetting that --x changes the caller’s copy | Off-by-one in the printed values | Pass x - 1 instead |
| Calling a function defined later without a prototype | Warning or wrong argument types | Add a forward declaration |
| Assuming a local and a global are the same object | Global never changes | Rename, for example with a g_ prefix |
Using (a, b) where a, b was intended | Only the last value is used | Read compiler warnings seriously |
Best Practices, Performance and Security
Best practices
- Keep side effects out of function arguments.
- Use different names for globals and locals, for example
g_levelversuslevel. - Declare mutually recursive functions with prototypes at the top of the file.
- Compile with
-Wall -Wextraand treat every warning as a question.
Performance: the printing order has no cost difference, but doing work after the recursive call prevents the tail-call optimisation, so the stack keeps growing. Security: side effects hidden in arguments make code review harder, and the order in which a compiler evaluates several arguments is unspecified, so an expression that modifies and reads the same variable in one call can behave differently between compilers.
Key Takeaways and Conclusion
- Code before the recursive call runs going down; code after it runs coming back.
- Pre-decrement in an argument changes the caller’s variable as well as the callee’s parameter.
- Mutual recursion needs a prototype for the function that appears first.
- The comma operator yields its rightmost operand; the compiler’s warning is a hint.
- A local variable hides a global with the same name.
Tracing recursive functions in C is a skill you build by drawing frames, not by guessing. Use the five-step routine on every exercise until it becomes automatic. In the next lecture we collect the compile errors that functions most often produce and read the real compiler messages.
Frequently Asked Questions
Why does a recursive print function show output in reverse order?
The statement after the recursive call runs only when the deeper call returns, so the deepest frame prints first and the first frame prints last.
What is the difference between direct and indirect recursion?
Direct recursion is a function calling itself. Indirect recursion is a cycle of two or more functions, such as A calling B and B calling A.
Does --x inside a function call change the original variable?
It changes the variable in the calling function, because the decrement is applied there before the value is copied into the parameter.
What does a comma expression return in C?
The value of its last operand, after evaluating every operand from left to right.
Can I access a hidden global from inside a function that declares a local with the same name?
Not by name. C has no scope-resolution operator, so rename one of the variables.
How do I get better at tracing recursive functions in C?
Draw each frame on paper, mark the base case, and replay the page from the deepest frame upward. Then confirm by running the program.
Free C Programming Course Continues
Next we study the most common function errors and read real compiler diagnostics together. It is all part of our free embedded C course.

2 Comments