Recursion

Hey!
I have some experiencie in programming Javascript, Java, C#, but almost nothing in C++.
I just would like to point it out that I thought it missed a good oportunity for explaining a little bit about recursion in the implementation of AskToPlayAgain(). Tell me if something is bad about it…

My version of the method:

1 Like

Hi @Rafael_Leal. I’d be cautious using recursion like this because you’re dealing with user input, and there’s no guarantee of an exit condition. You could end up with a stack overflow (because every time AskToPlayAgain() calls itself, another return address is pushed on to the call stack). I try to use recursion for problems where recursion is a “natural fit”, as it’s very easy to introduce bugs when using recursion.

This would achieve the same result without using recursion:

#include <iostream>

using namespace std;

constexpr int UPPERCASE_MASK = 223;

bool PlayAgain()
{ 
  string Response = ""; 
  do {
    cout << "Try again? (Y/N): ";
    getline(cin, Response);
    Response[0] &= UPPERCASE_MASK;
  }
  while (Response[0] != 'Y' && Response[0] != 'N');

  return Response[0] == 'Y';
}


int main()
{
  do {
    cout << "Hello there..." << endl;
  }
  while (PlayAgain());

  return 0;
}