Date: Mon, 31 Jan 2005 23:26:09 +1100 From: Andrew Reilly <andrew-freebsd@areilly.bpc-users.org> To: Paul Richards <paul@originative.co.uk> Cc: arch@freebsd.org Subject: Re: c99/c++ localised variable definition Message-ID: <20050131122609.GA83556@gurney.reilly.home> In-Reply-To: <20050131102630.GJ61409@myrddin.originative.co.uk> References: <20050128173327.GI61409@myrddin.originative.co.uk> <20050131102630.GJ61409@myrddin.originative.co.uk>
next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, Jan 31, 2005 at 10:26:30AM +0000, Paul Richards wrote:
> 3) Usage in for loops may be more useful than other uses.
[snip]
> I think the loop usage though is one clear example where it is
> clearer. I think there are others as well; where the usage of the
> variable is clearly localised it is much easier to see a local
> definition than to have to jump back and forth to find out what
> variables are.
I'd just like to raise a dissenting voice to this particular
point. I find the for-loop initialization syntax a pernicious
source of errors, mainly because of the non-intuitive scope of
the definition. I.e., it looks like it's equivalent to "int i;
for (i = 0;;)" but it isn't.
If you carelessly c++-ify a loop like:
for (int i = 0; i < N; i++)
{
if (some_condition(i)) break;
}
do_something_with(i); /* use finishing index */
you can miss the fact that the value of i is used outside of the
loop. The newly created scope for "i" shadows the presumably
pre-existing definition of i at the top of the function, which
is what do_something_with() gets to see.
Const friendliness and some minor economy of thought are perhaps
valid benefits of this style, but I don't think sufficient to
change the style.
Cheers,
--
Andrew
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20050131122609.GA83556>
