关于C++递归函数回溯阶段cout输出递增数值的疑问
Understanding the Backtracking Output in Your Recursive Function
First, let's restate your code for reference:
void PrintTest(int test) { if (test < 1) { return; // Exit condition, known as "base case" } else { cout << test << " "; PrintTest(test-1); cout << test << " "; } } int main() { int a; cout << "Enter a number preferably between 2 and 9: "; cin >> a; PrintTest(a); }
Great question—this is a classic example of how recursion has two distinct phases: the "descent" (where we call the function repeatedly until hitting the base case) and the "ascent" (backtracking, where we finish executing the remaining code in each paused function call). Let's break this down with a concrete example to make it click.
Step-by-Step Execution (Using Input = 3)
Every time you call PrintTest(test), it creates a separate instance of the function with its own copy of the test parameter. Here's exactly what happens:
Descent Phase (Going "Down" the Recursion)
- Call 1:
PrintTest(3)- Hits the
elsebranch - Runs
cout << 3 << " ";→ Output so far:3 - Calls
PrintTest(2)(this pausesPrintTest(3)until the new call completes)
- Hits the
- Call 2:
PrintTest(2)- Hits
else - Runs
cout << 2 << " ";→ Output so far:3 2 - Calls
PrintTest(1)(pausesPrintTest(2))
- Hits
- Call 3:
PrintTest(1)- Hits
else - Runs
cout << 1 << " ";→ Output so far:3 2 1 - Calls
PrintTest(0)(pausesPrintTest(1))
- Hits
- Call 4:
PrintTest(0)- Triggers the base case (
test < 1) → immediatelyreturns, ending this call
- Triggers the base case (
Ascent Phase (Backtracking "Up" to the Original Call)
Now we go back to each paused function instance and run the code that came after the recursive call:
- Resume
PrintTest(1)- Picks up right after
PrintTest(0); - Runs
cout << 1 << " ";→ Output so far:3 2 1 1 - This instance finishes, returns to
PrintTest(2)
- Picks up right after
- Resume
PrintTest(2)- Picks up right after
PrintTest(1); - Runs
cout << 2 << " ";→ Output so far:3 2 1 1 2 - This instance finishes, returns to
PrintTest(3)
- Picks up right after
- Resume
PrintTest(3)- Picks up right after
PrintTest(2); - Runs
cout << 3 << " ";→ Final Output:3 2 1 1 2 3
- Picks up right after
Key Clarifications
- No new function calls during backtracking: We aren't invoking
PrintTestagain when we backtrack—we're just completing the work of function instances that were already started and paused earlier. - Each instance retains its
testvalue: WhenPrintTest(1)resumes, itstestparameter is still1(it never changed). The secondcoutdoesn't need a+1because it's just outputting the original value that was passed to this function instance. - Recursion = "Depth-first execution": The first set of
couts runs as we dive deeper into recursion, and the second set runs as we climb back up, using the preserved parameter values from each call.
内容的提问来源于stack exchange,提问作者UniverseX
相关产品推荐
相关产品推荐

