You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归函数中两个递归调用的执行顺序疑问及代码无限输出异常排查

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 the print function pauses completely. It won't move on to the newline or print(num+1) until that entire print(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:
    1. Print the current num value
    2. Fully run the entire recursive chain of print(num-1) (all the way down to num=1, which triggers the return, then unwinds back to the original call)
    3. Print a newline
    4. Fully run the entire recursive chain of print(num+1)

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:

  1. When you call print(23), it prints 23 then calls print(22). This continues all the way down to print(1), which hits the return condition and stops.
  2. Now the recursion unwinds: each previous call resumes where it left off. For example, print(2) resumes after print(1) returns, prints a newline, then calls print(3).
  3. This pattern continues as we unwind and start calling print(num+1) for each number up to print(32):
    • print(32) prints 32, calls print(31) (which runs its full chain and returns), prints a newline, then calls print(33).
    • print(33) prints 33, calls print(32) (which again prints 32, calls print(31) and returns, prints a newline, then calls print(33)).
  4. Now we're stuck in a circular loop: print(32) → print(33) → print(32) → print(33)... forever. Neither 32 nor 33 hits your exit condition (num ==1 or num==100), so the recursion never stops, and you keep seeing 32 printed 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:32:29