Article View: comp.std.c++
Article #2049Re: Scope of variables declared in if/while/for
From: Joe Buck
Date: Tue, 26 Sep 1995 20:26
Date: Tue, 26 Sep 1995 20:26
43 lines
2396 bytes
2396 bytes
rmartin@rcmcon.com (Robert Martin) writes:
>In reading the WP I see that the scope of variables declared in 'for'
>statements is now identical with the scope of variables declared in
>'if' and 'while' statements...
>Do I have this right? If so, doesn't this break a lot of old C++
>programs that depended upon variables declared in the 'for' statement
>being local to the enclosing scope.
Yes, this change breaks a great deal of old code. As best I can
determine, when gcc-2.7.0 implemented this change every significant-sized
C++ program I'm aware of (including all of the more popular freely
redistributable C++ programs) had at least some breakage; hundreds of
distinct cases are often found. That's why it's so important to provide
backward compatibility flags (-fno-for-scope, in the case of gcc).
It is possible to use the old scope rule (together with warnings) in
the very common case where there would otherwise be a reference to
an undefined variable when the new rule is used. gcc-2.7.1 will
do this. Thus in Robert's example
>for (int i=0; i<100; i++)
>{
> // expressions using i;
>}
>
>if (i == 100) // loop ran to end.
provided that there is no i in a more global scope, the compiler will
issue a warning and then proceed using the old rule. This permits most
old programs to build. This can't be done if i is an object with a
destructor rather than an int.
--
-- Joe Buck <jbuck@synopsys.com> (not speaking for Synopsys, Inc)
Anagrams for "information superhighway": Enormous hairy pig with fan
A rough whimper of insanity
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]
Technical Details
Message-ID:
<449ncf$ds7@hermes.synopsys.com>Path:
arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!taumet!clamageReferences:
<MATT.95Sep25095657@physics2.berkeley.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!taumet!clamage From: jbuck@Synopsys.COM (Joe Buck) Newsgroups: comp.std.c++ Subject: Re: Scope of variables declared in if/while/for Date: 26 Sep 1995 20:26:09 GMT Organization: Synopsys Inc., Mountain View, CA 94043-4033 Approved: clamage@eng.sun.com (comp.std.c++) Message-ID: <449ncf$ds7@hermes.synopsys.com> References: <MATT.95Sep25095657@physics2.berkeley.edu> NNTP-Posting-Host: taumet.eng.sun.com Content-Type: text X-Nntp-Posting-Host: deerslayer.synopsys.com Content-Length: 1562 X-Lines: 39 Originator: clamage@taumet