递归调用后用代码进行递归

use*_*cow 1 recursion

我试图理解递归是如何工作的,但还有一件事我不太明白:当递归函数本身内的递归调用之后有代码时,递归函数如何工作。请参阅下面的示例伪代码以帮助理解我的意思。我确切的问题是递归调用之后的代码将以什么顺序(即何时)执行。 机器会记录递归调用,在调用后执行剩余的代码(打印“完成”),然后返回并实际执行整个递归调用,还是机器会在到达该调用后立即执行递归调用行并仅在递归触底后执行最后一位代码(打印“完成”)? 何时以及多少次会打印“done”?

void recurse()
{
  print "hello world";
  for i = 0 up to 2
    recurse();

  print "done";
}
Run Code Online (Sandbox Code Playgroud)

小智 6

递归调用在其下面的任何代码之前运行。一旦返回,它将返回并完成其余的代码。所以发生的事情是

"hello world"
i = 0
"hello world"
i = 0
"hello world"
...
Run Code Online (Sandbox Code Playgroud)

永远。因为您没有将 的值传递i给下一个递归函数,所以您的代码将永远运行,每次都以 重新启动i=0

让我们假设您i确实正确地传递给了递归函数:

void recurse(i) {
    // is i still < 2?
    if (i < 2) {
        print "hello world";
        recurse(i+1);
        print "done";
    }

recurse(0);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将得到:

i = 0
"hello world"
    i = 1
    "hello world"
        i = 2
    "done"
"done" 
Run Code Online (Sandbox Code Playgroud)