Mail Archives: djgpp/1997/06/20/21:35:11
Chris wrote:
>
> I read, or may have misread, something one time about the scope of a
> variable. I read that if a variable was declared in a for/while loop,
> that its life was for the loop only. Example....
>
> while( int i = 1)
> {
> //whatever
> }
>
> But the other day I compiled a program and it complained that the
> variable was declared earlier, but the earlier declaration was in a
> for loop.
>
> My question is, what is the exact scope of a variable that is declared
> in a loop? Just wondering so I'll know what's legal, and what's not.
The scope is the statement controlled by the while(). In this case, the
statement is a compound statement, delimited by { and }. The reason that
this verbosity is important is this:
for( int i = 0; i < 10; i++ )
cout << i;
Here, too, the scope of i is the controlled statement. This 'i' is not
available in any subsequent code.
This gets confusing, though, because the rule used to be that i's scope
was the rest of the block in which the for statement occurred. There's a
lot of code that relies on this behavior, so some compilers haven't yet
changed how they handle this, and some compilers provide a switch so
that you can choose how variables like this are handled.
If you're writing code that has to compile with a compiler that only
provides the old behavior, you may be better off not using this feature.
That way you won't have to rewrite your code when you switch to a
compiler that handles this in accordance with the new rule.
-- Pete
- Raw text -