From: Pete Becker Newsgroups: comp.os.msdos.djgpp,comp.lang.c++ Subject: Re: Scope of a variable Date: Fri, 20 Jun 1997 11:09:20 -0400 Organization: Pete Becker Consulting Lines: 37 Message-ID: <33AA9D20.1BF2@acm.org> References: <33aa381b DOT 26282298 AT supernews DOT scsn DOT net> Reply-To: petebecker AT acm DOT org NNTP-Posting-Host: bos-ip-3-217.ziplink.net Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk 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