Article View: comp.std.c++
Article #2484Re: New treatment of 'for (int i ...'
From: Fergus Henderson
Date: Thu, 09 Nov 1995 07:40
Date: Thu, 09 Nov 1995 07:40
54 lines
2589 bytes
2589 bytes
sjc@netcom.com (Steven Correll) writes:
>What was the rationale for this change, which from here looks quite
>gratuitous?
See pages 99-100 of "Design and Evolution of C++".
Basically the reason is that the scope of names should be kept as small
as possible. The reason that finally persuaded the committee to make
the change was consistency. The committee added the ability to declare
a variable in an `if' statement, particularly for use with
dynamic_cast:
if (Foo *foo_p = dynamic_cast<Foo *>(p)) {
...
else if (Bar *bar_p = dynamic_cast<Bar *>(p)) {
...
} else {
...
}
Here the scope of `foo_p' and `bar_p' is only their respective branches
of the if-then-else. It would be very confusing if there was one rule
for `if' and a different rule for `for'.
>The change makes it difficult to write programs that will work in both old
>compilers and new ones while implementors scurry to catch up with the
>ever-inventive committee.
There is a neat hack which gives you the new behaviour with old compilers:
#ifdef USE_HACK_FOR_NEW_FOR_SCOPE
#define for(x) if (0) ; else for(x)
#endif
(Did I get that right this time?)
I think this hack is Andrew Koenig's idea. The reason this works is
that there is an implied scope around the statement in the `else' part
of an if-then-else. (It might not work with really ancient compilers
that don't implement that rule, but probably nothing else will work
with those compilers either.)
So you can just chuck the above hack in a head file, write code as if
your compiler implemented the new rules, and if you are using an old
compiler, compile with `-DUSE_HACK_FOR_NEW_FOR_SCOPE'.
--
Fergus Henderson WWW: http://www.cs.mu.oz.au/~fjh
fjh@cs.mu.oz.au PGP: finger fjh@128.250.37.3
---
[ 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:
<9531318.2076@mulga.cs.mu.OZ.AU>Path:
arc1-ca.pugleaf.net!in1.uu.net!bounce-backReferences:
<47itjt$65m@lhc.nlm.nih.gov> <sjcDHqMKM.MBG@netcom.com>Show Full Headers
Complete Article Headers
Approved: fjh@cs.mu.oz.au Date: 09 Nov 95 07:40:33 GMT From: fjh@munta.cs.mu.OZ.AU (Fergus Henderson) Message-ID: <9531318.2076@mulga.cs.mu.OZ.AU> Newsgroups: comp.std.c++ Organization: Computer Science, University of Melbourne, Australia Path: arc1-ca.pugleaf.net!in1.uu.net!bounce-back References: <47itjt$65m@lhc.nlm.nih.gov> <sjcDHqMKM.MBG@netcom.com> Subject: Re: New treatment of 'for (int i ...' X-Auth: PGPMoose V1.1 PGP comp.std.c++ iQBFAgUBMKGwhuEDnX0m9pzZAQFXiwGAiboIQVDooz86SIJAWRvQ1vpg58rZ7/r5 H5rbOxiNWlZ5h3XA1epnSqlQxQgUH5WP =tqBt