GetValidGuess() without a do-while loop

I’m just putting this out there in case somebody would like to see alternatives to the do-while loop (I had initially done this with a dummy bool that changed when it reached “OK” status). Please let me know if you have any questions or comments (especially if you think this is a bad idea)! I already tested it out and it works.

Ftext GetValidGuess()
{
Ftext UserGuess = “”;
std::cout << "\nTry " << BCGame.GetCurrentTry() << ". ";
std::cout << "Please enter your guess: ";
getline(std::cin, UserGuess);
EWordStatus Status;

Status = BCGame.CheckGuessValidity(UserGuess);
switch (Status)
{
case EWordStatus::Wrong_Length:
std::cout << “Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n”;
return GetValidGuess();
break;
case EWordStatus::Not_Isogram:
std::cout << “Please enter an isogram. An isogram is a word where no letters repeat.\n”;
return GetValidGuess();
break;
case EWordStatus::Not_Lowercase:
std::cout << “Your word needs to be in all lowercase!\n”;
return GetValidGuess();
break;
default:
return UserGuess;
break;
}
}

I think a loop makes more sense than recursion for this problem, this is theoretically infinite and having a call stack that go on indefinitely is probably a bad idea.

Wouldn’t the while loop also count as infinite?

And I think I understand what you mean by “call stack”. Is it all the function calls that get put “on hold” until an actual value is finally returned? I’m guessing this could end up as a processing/memory problem for bigger programs.

“Wouldn’t the while loop also count as infinite?”
Yes, but if you are using recursion, the previous call would still be in memory, so each time you recursively call GetValidGuess you would be creating another std::string Guess and EWordStatus Status on the stack.

As for a call stack I’m not sure I’m able to explain it very well, though maybe this picture of it in Visual Studio’s debugger will help

It’s last-in first-out structure. So here you can see main() called PlayGame() and that called GetValidGuess() which then called GetValidGuess again and a return would go back to the previous call.

This computerphile also goes over the stack, though it’s part of a seperate topic but still good.

1 Like

I understand. Thank you for the feedback!

Privacy & Terms