Since I got into Scala I started writing functions using tail recursion, and learned that C++ compilers also support it, and even optimize tail recursive functions. Now I'm curious as to how reliable that optimization is, and is it okay to use it for things such as my main loop or command prompt?
Traditionally I've written command prompts like this:
bool running = true;
string input;
while(running_){
input = getInput();
executeCommand(input);
if(input == "quit") running_ = false;
}
Now would it be a bad thing to replace this with a tail recursive function like this?
string input = "nothing";
void parseInput(){
if(input != "nothing") executeCommand(input);
getline(cin, input);
if(input != "quit") parseInput();
}
TCO (tail-call optimization) is applied with different level of reliability by different compilers. In your particular case you make it even harder for compiler by not returning immediately after the call inside the branch. Compiler will have to take an extra step to make sure there is no code which will be executed after the call is done.
To make sure TCO did happen you have to rely on your best friend. Your best friend here is asm output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With