While loop challenge Triplex

So I put my while loop here at the challenge and it worked fine, just wondering why that is and why its better to put it in the main function?

void PlayGame()
{
   
 // delcare 3 number code

  const int CodeA = 1;
  const int CodeB = 0;
  const int CodeC = 7;

  const int CodeSum = CodeA + CodeB + CodeC;
  const int CodeProduct = CodeA * CodeB * CodeC;

 //Print CodeSum and CodeProduct to the terminal
  
  std::cout << "\n The code to disarm the bomb has 3 digits.";
  std::cout << "\n The codes add-up to: " << CodeSum;
  std::cout << "\n The digits multiply makes: " << CodeProduct << std::endl;
 
 //Store player guess
  int GuessA, GuessB, GuessC;
  std::cin >> GuessA >> GuessB >> GuessC;
 
  int GuessSum = GuessA + GuessB + GuessC;
  int GuessProduct = GuessA * GuessB * GuessC;

  //Check if player Guess is correct
  if(GuessSum == CodeSum && GuessProduct == CodeProduct)
    {
     std::cout<<"\nYou Have Disarmed the bomb!";
    }
    else
    {
     std::cout<<"\nYou blew up!";
    }
    while(PlayGame)
    {
   PlayGame();
    }
}

int main()
{
 PrintIntroduction();
 PlayGame();
 return 0;
    
}

There’s two problems with this piece of code

  1. This is using address of the function PlayGame for the condition. This is being implicitly being converted to bool which is always be true. Compilers typically warn on this.

  2. This is an infinite recursive loop. Every time this function calls itself it’s making a new stack frame which means new variables are created for CodeA, CodeB, CodeC etc. and the previous ones are still kept in memory. Given enough rounds this result in a stack overflow which means you’ve run out of memory (on the stack)…

2 Likes

Okay that makes a lot of sense, thank you for your insight! I like asking so I can make sure I understand completely. :thinking: :grinning:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms