(expression 1)
{statement 1}
.
.initialize vars for next loop
.
(expression 2)
{statement 2}
If I am initializing vars in first statement for second loop what is my scope? Both loops or the nested loop. In this example the game is restarted/reinitialized
with the first loop so that var initialization in first loop is probably appropriate.
A { introduces a new scope. Variables introduced in that scope are invisible to the enclosing scope. So a good rule of thumb is to declare variables in the smallest scope in which they are used.
1 2 3 4 5 6 7 8 9 10 11 12
{
int n = 12;
cout << "n = " << n << "\n";
{
int x = 3;
n += x;
cout << "x = " << x << "\n";
}
// x no longer exists
cout << "n = " << n << "\n";
}
// n no longer exists
{older scope
{new scope
...int x = 3;
}
{
x can be seen within new scope but not from older scope
is that correct?
1 2 3 4 5 6 7 8 9 10 11 12
{
int n = 12;
cout << "n = " << n << "\n";
{
int x = 3;
n += x;
cout << "x = " << x << "\n";
}
// x no longer exists
cout << "n = " << n << "\n";
}
// n no longer exists
That is helpful. Checking to see if my understanding is ok.