Mail Archives: djgpp/1997/06/21/01:12:59
You can declare variables in almost any place using C++ (not C). Their
life is only within the scope they are declared. As you noted it can be in
for loop ex. for(int i=0; i<3; i++){something} However you can not use
this variable outside the for loop braces. The problem you faced is
overshadowing of variables. You probably had a variable with the same name
and tried to declare a new variable. Ex.
main()
{
int i;
for (int i=0; i<3; i++)
printf("%d", i);
}
This is illigal.
On Fri, 20 Jun 1997, 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.
>
> Thanks,
> Chirs
>
- Raw text -