• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Basic C++ variable scope question...

Nevyn522

Senior member
Hey -

I thought I knew the answer to this, but I just got a weird error trying to do this, so...

Observe the following code:

for (int n = 1; n <= 100; n++)
{
//Do stuff
}

//Do more stuff

for (int n = 1; n <= 100; n++) //Yes, they have to be separate loops
{
// Do another loop
}

------

Now, I thought scope is limited within a for loop... meaning that once the first for loop terminates, n is out of scope/doesn't exist. Ergo, I would need to create it again. I was CERTAIN that's what happened, and yet when I tried to compile the above code with MS VC++6 SP4, I got a compiler error on the second for loop, saying that n was already initialized.

Is this is just a compiler optimization bug, or am I off on the scope issue?

Thanks,
Andrew
 
If this is within the same function(C) or method(C++), &quot;n&quot; only can only be created once. Therefore, &quot;n&quot; goes out of scope when out of the function or method.
 
Try this:

for (n = 17221100; n <= 17221500; n++)
{
int x = 5;
//Other stuff
}

//other stuff

for (n = 17221100; n <= 17221500; n++)
{
x = 10;
//Other stuff
}

--

Compile it -- x in the second loop is an undeclared identifier.

I would have sworn that anything declared in the for loop initialization was the same way.
 
On the other hand, why would you ever declare and initialize a local variable in a for loop? In this case, x would equal 5 every iteration.
 
Variables declared inside a loop header stay in existance until the function/procedure ends. Variables declared inside the body of the loop only exist in that loop. Eg:

for (int n = 0; n < 10; n++)
{
int x;
}

for (n = 0; n < 10; n++)
{
int x;
}
 
Back
Top