Article View: net.lang.c++
Article #166Re: Unintuitive semantics for initializing in for statements
From: KW Heuer
Date: Wed, 23 Apr 1986 17:47
Date: Wed, 23 Apr 1986 17:47
29 lines
2213 bytes
2213 bytes
In article <5334@alice.uUCp> alice!shopiro (Jonathan Shopiro) writes:
>The advantage in having the iteration variable declared in a for
>statement remain accessible is that you can test its value after
>the end of the loop.
True, although I seldom (if ever) use it -- if it was a simple counting
loop as in the example, I already know the terminating value unless a
break statement was reached ("for (i=0; i<N; ++i) if (a[i]==X) break;"),
and I find that type of code ugly because it usually has to be followed
by a second test of the same condition ("if (i<N)...; else notfound();").
I much prefer "for (i=0; i<N; ++i) if (a[i]==X) return i; return NONE;"
which can be nicely embedded in a routine of its own. (Perhaps the newer
compilers can even code it inline? The last one I saw couldn't handle
loops in an inline function.) But I digress.
I support the idea of having the interation variable go out of scope at
the end of the for statement. It makes sense, since it was declared as
part of that statement. (Yes, the alternative also makes sense because
of the definition of "for".) I would find it quite useful. For those
cases where I need the value outside the for, I'd prefer to declare the
variable outside anyway.
One last point. If the compiler knows that the control variable is out
of scope after the loop, and is not modified within the loop, some neat
optimizations may be possible. This is not too useful for the compilers
that generate C output, but may be of interest for implementations that
generate assembly language.
Karl W. Z. Heuer (ihnp4!bentley!kwh), The Walking Lint
Technical Details
Message-ID:
<738@bentley.UUCP>Path:
arc1-ca.pugleaf.net!utzoo!watmath!clyde!cbosgd!ihnp4!bentley!kwhReferences:
<5334@alice.uUCp>Show Full Headers
Complete Article Headers
Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 ggr 10/10/85; site bentley.UUCP Path: arc1-ca.pugleaf.net!utzoo!watmath!clyde!cbosgd!ihnp4!bentley!kwh From: kwh@bentley.UUCP (KW Heuer) Newsgroups: net.lang.c++ Subject: Re: Unintuitive semantics for initializing in for statements Message-ID: <738@bentley.UUCP> Date: Wed, 23-Apr-86 12:47:09 EST Article-I.D.: bentley.738 Posted: Wed Apr 23 12:47:09 1986 Date-Received: Thu, 24-Apr-86 07:42:13 EST References: <5334@alice.uUCp> Organization: AT&T Bell Laboratories, Liberty Corner Lines: 29