In course " Unreal Engine C++ Developer: Learn C++ and Make Video Games" under Section 3 #63 when discussing early returns, Mike goes over returning early so that the rest of our code doesn’t need to execute the rest of the if/else if/else statements. If I understand correctly though only one of these conditions will be able to be met, which should mean that the rest of the code within the function shouldn’t execute anyways. So for example
func1{
if (condition1){do thing}
else if (condition2){do other thing}
else{do third thing}
}
This should mean only one condition will be met and the rest of the code will not be run anyways. I can understand why he has implemented the return when the game is over as we want to exit to the top level and restart the game, but it does not make sense to me to otherwise return within the if statement when checking the length of guess vs hiddenword.
In my example below, I believe that using the return would actually be detrimental, as this would mean that we would never check if lives <= 0 and subsequently would not end the game on that turn.
void UBullCowCartridge::ProcessGuess(FString Guess)
{
if (HiddenWord.ToLower() == Guess.ToLower())
{
PrintLine(TEXT("Nice guess, the answer was -\n%s"), *HiddenWord);
EndGame();
return;
}
// check isogram, how to parse the input?
else if (Guess.Len() != HiddenWord.Len())
{
if (Guess.Len() < HiddenWord.Len())
{
PrintLine(TEXT("Your input is shorter than the word"));
}
else
{
PrintLine(TEXT("Your input is longer than the word"));
}
PrintLine(TEXT("Your remaining lives - %i"), --Lives);
}
else
{
PrintLine(TEXT("You guessed wrong, but have the correct\namount of letters!"));
PrintLine(TEXT("Your remaining lives - %i"), --Lives);
}
if (Lives <= 0)
{
PrintLine(TEXT("You have lost the game and are out of\nlives!\nThe answer was %s "), *HiddenWord);
EndGame();
}
}
Can anyone clear this up for me or explain where my thought process has gone wrong?