Why was this allowed?

for (int count =1; count <= NUMBER_OF_TURNS; count++){
string Guess  = GetGuess();
(...)
}

Apologies for being a code-nazi, but I can see the Guess string being re-declared inside a ‘for’ loop. That’s something we’ve covered earlier as a wrong thing to do. I would think that you declare a variable once outside a loop and then assign values to it, however many times you like. Something along the lines of:

string Guess  = "";
for (int count =1; count <= NUMBER_OF_TURNS; count++){
Guess  = GetGuess();
(...)
}

I was actually surprised the console didn’t crash on the second try. Without the loop, the code would look like this:

string Guess = GetGuess(); 
string Guess = GetGuess();
string Guess = GetGuess();
string Guess = GetGuess();
string Guess = GetGuess();

And we’ve covered that earlier that the code wouldn’t compile.

Question - Why did the compiler allow for it?

Every time the loop finishes in run-time, all Variables created inside it
(like the string Guess)
get destroyed.

When it runs another time, there is no varaible “string Guess”, since it has been destroyed before, so we can create another one without problems (it’s a run-time thing, not compile-time)

It’s all to do with the scope of the variable, basically where it “lives” in a way. Variables only live in the block of code that they are declared in and when that block of code finishes running the variable “dies”. Variables can only be accessed when they are “live”. As Daniel pointed out the block of code starts and end each loop, so the variable is born, lives and dies each time through the loop.

Privacy & Terms