delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/21/01:12:59

Date: Sat, 21 Jun 1997 00:13:22 -0500 (CDT)
From: Andrew Deren <aderen AT eecs DOT uic DOT edu>
To: Chris <ckeenan AT scsn DOT net>
cc: djgpp AT delorie DOT com
Subject: Re: Scope of a variable
In-Reply-To: <33aa381b.26282298@supernews.scsn.net>
Message-ID: <Pine.SUN.3.95.970621001002.22827A-100000@ernie.eecs.uic.edu>
MIME-Version: 1.0

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019