条件加倍时的递归调用

Recursive calls when the condition is doubled

本文关键字:递归 调用 条件      更新时间:2023-10-16

这里有一个问题:这个程序重复了两次if条件;递归调用将如何在每个if块中工作,这似乎有点不那么简单。

我试图了解从第一个递归调用的执行是否会跳转到第二个 if 块,或者如果对于 c 的每个值,还会有另外两个递归调用,因为该函数有两个递归调用; 这里的变量 c 的值意味着在函数内部通过减法运算进行处理后。

谢谢大家!

#include <iostream>
using namespace std;
void ex(char c);
void ex(char c) { 
if (c >'a') { 
ex(c-1);
}  
cout<< c;    
if (c>'a') { 
ex(c-1);
} 
}
int main()
{
ex('c');
}

递归调用 与非递归调用一样,被调用的函数从头开始。

如果编译器检测到递归调用是终端,则新调用不会添加到堆栈中,而是替换为等效的跳转(但除了有关堆栈管理的几条指令外,仍然在开始时进行(。您的第二个递归调用是终端。

您可以使用调试器或修改代码以查看调用以具有:

#include <iostream>
using namespace std;
void ex(char c, string indent = string()) { 
cout << indent << "enter with " << c << endl;
if (c >'a') { 
ex(c-1, indent + "@");
}  
cout<< indent << c << endl;    
if (c>'a') { 
ex(c-1, indent + "$");
} 
cout << indent << "exit with " << c << endl;
}
int main()
{
ex('c');
}

编译和执行:

pi@raspberrypi:/tmp $ g++ a.cc
pi@raspberrypi:/tmp $ ./a.out
enter with c
@enter with b
@@enter with a
@@a
@@exit with a
@b
@$enter with a
@$a
@$exit with a
@exit with b
c
$enter with b
$@enter with a
$@a
$@exit with a
$b
$$enter with a
$$a
$$exit with a
$exit with b
exit with c
pi@raspberrypi:/tmp $ 

缩进的深度是递归调用的深度,@/$ 指示调用的位置