Is it correct to declare a variable inside a loop?

In the PlayGame() function, the Guess variable is declared inside the for loop. Can it cause some kind of problems? I do the declaration once before the loop, and inside the value for GetGuess() is assigned to the previous declared variable. It seems more correct to me, but I don’t know if it is or if it doesn’t matter.

Can you post a code snippet? I would be happy to take a look.

For sure. Here it is:

void PlayGame()
{
	//number of times player is asked for guesses
	constexpr int LIMIT = 5;

	string GuessResult = "";
	// repeat the guess back to them
	for (int count = 0; count < LIMIT; count++) {
		GuessResult = GetGuess();
		PrintGuess(GuessResult);
	}
	return;
}

Original loop:

  // repeat the guess back to them
   for (int count = 0; count < LIMIT; count++) {
    	string GuessResult = GetGuess();
    	PrintGuess(GuessResult);
    }

Most compilers would treat this the same from a performance standpoint. For code clarity the original loop is better. It is better to have the variable fall out of scope and generate a compiler warning rather than hang around inside the rest of the function to be used with who knows what value leftover from the loop in it.

2 Likes

Ok, thanks for the explanation :smiley:

Privacy & Terms