递归函数中两个递归调用的执行顺序疑问及代码无限输出异常排查
Answers to Your Recursion Questions
First, let's pull up your recursive function for reference:
void print(int num){ if(num == 1 || num == 100){ return; } std::cout << num ; print(num-1); std::cout << std::endl; print(num+1); return; }
1. Are Recursive Calls Executed Simultaneously or Sequentially?
In standard single-threaded code like this C++ function, recursive calls run sequentially—they never happen at the same time. Here's how it works step by step:
- When your code hits
print(num-1), the current execution of theprintfunction pauses completely. It won't move on to the newline orprint(num+1)until that entireprint(num-1)call chain finishes (meaning every nested recursive call under it runs all the way to a return and unwinds back up). - So for your function, the flow is strictly:
- Print the current
numvalue - Fully run the entire recursive chain of
print(num-1)(all the way down tonum=1, which triggers the return, then unwinds back to the original call) - Print a newline
- Fully run the entire recursive chain of
print(num+1)
- Print the current
There's no "parallel" printing happening—each recursive call block must finish before the next part of the function runs.
2. Why Does num=23 Cause Infinite Output of 32?
Let's trace the path that leads to this infinite loop:
- When you call
print(23), it prints23then callsprint(22). This continues all the way down toprint(1), which hits the return condition and stops. - Now the recursion unwinds: each previous call resumes where it left off. For example,
print(2)resumes afterprint(1)returns, prints a newline, then callsprint(3). - This pattern continues as we unwind and start calling
print(num+1)for each number up toprint(32):print(32)prints32, callsprint(31)(which runs its full chain and returns), prints a newline, then callsprint(33).print(33)prints33, callsprint(32)(which again prints32, callsprint(31)and returns, prints a newline, then callsprint(33)).
- Now we're stuck in a circular loop:
print(32)→print(33)→print(32)→print(33)... forever. Neither32nor33hits your exit condition (num ==1ornum==100), so the recursion never stops, and you keep seeing32printed repeatedly.
To fix this, you'd need an exit condition that catches values outside your intended range—like checking if num < 1 || num > 100 instead of only exact matches for 1 and 100.
内容的提问来源于stack exchange,提问作者Pranav_Mundhra
相关产品推荐
相关产品推荐

