gpt4 book ai didi

c++ - 斯卡拉/C++ : Tail Recursive function instead of input loop

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:34 31 4
gpt4 key购买 nike

自从接触到Scala后,我就开始使用尾递归写函数,了解到C++编译器也支持尾递归,甚至优化了尾递归函数。现在我很好奇这种优化的可靠性如何,是否可以将它用于我的主循环或命令提示符之类的事情?

传统上我写的命令提示符是这样的:

bool running = true;
string input;
while(running_){
input = getInput();
executeCommand(input);
if(input == "quit") running_ = false;
}

现在用这样的尾递归函数替换它是不是一件坏事?

string input = "nothing";
void parseInput(){
if(input != "nothing") executeCommand(input);

getline(cin, input);
if(input != "quit") parseInput();
}

最佳答案

TCO(尾调用优化)被不同的编译器以不同的可靠性级别应用。在您的特定情况下,您通过在分支内调用后不立即返回来使编译器更加困难。编译器必须采取额外的步骤来确保没有代码在调用完成后执行。

要确保 TCO 确实发生,您必须依赖您最好的 friend 。这里最好的 friend 是 asm 输出。

关于c++ - 斯卡拉/C++ : Tail Recursive function instead of input loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32511017/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com