Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala/C++: Tail Recursive function instead of input loop

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();
}
like image 289
BigBadWolf Avatar asked Oct 30 '22 19:10

BigBadWolf


1 Answers

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.

like image 54
SergeyA Avatar answered Nov 08 '22 07:11

SergeyA