条件加倍时的递归调用
Recursive calls when the condition is doubled
这里有一个问题:这个程序重复了两次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 $
缩进的深度是递归调用的深度,@/$ 指示调用的位置
相关文章:
- 返回递归调用和仅递归调用的区别
- 使用静态变量的递归调用的不同输出
- 复制构造函数中的递归调用
- 为什么编译器将其解析为函数指针而不是递归调用?
- 如何在 c++ 的类中递归调用函数方法?
- 了解使用堆栈实现队列的递归调用机制
- 如何通过函数指针递归调用类成员函数?
- 条件加倍时的递归调用
- 对可变参数函数的递归调用的链接器错误
- 将多个非原始递归调用转换为迭代解决方案
- 分段错误(核心转储)错误C++递归调用
- 无全局变量或功能参数的递归调用
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- C - 为什么合并函数在递归调用后会逆转数组
- 递归调用中出现错误"[Error] expression list treated as compound expression in initializer [-fpermissive]"
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- C++中具有 100000 个递归调用的运行时错误
- 递归调用可变参数模板函数重载时的不明确调用
- 如何在 c++ 中递归调用类
- 带有两个递归调用的递归算法的时间复杂性