Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 1 Feb 2005 20:43:31 +0000
From:      Paul Richards <paul@originative.co.uk>
To:        Marcel Moolenaar <marcel@xcllnt.net>
Cc:        arch@freebsd.org
Subject:   Re: c99/c++ localised variable definition
Message-ID:  <20050201204331.GH61409@myrddin.originative.co.uk>
In-Reply-To: <fa820cbe585add3bebb31954175460f3@xcllnt.net>
References:  <20050128173327.GI61409@myrddin.originative.co.uk> <20050131102630.GJ61409@myrddin.originative.co.uk> <20050201180624.GB19624@funkthat.com> <20050201190416.GG61409@myrddin.originative.co.uk> <fa820cbe585add3bebb31954175460f3@xcllnt.net>

next in thread | previous in thread | raw e-mail | index | archive | help
On Tue, Feb 01, 2005 at 12:30:37PM -0800, Marcel Moolenaar wrote:
> On Feb 1, 2005, at 11:04 AM, Paul Richards wrote:
> 
> >>And wonder why i gets such a strange value...  It appears that unless
> >>you have WARNS=4 set, warnings about:
> >>t.c:10: warning: declaration of 'i' shadows a previous local
> >>
> >>don't show up.  So, I would say we HAVE to get the tree building with
> >>WARNS=4 and -Werror before we let this into style(9)...
> >
> >The issue with shadowing outer scope variables is only an issue if
> >you need to access them. If your only using the syntax for loop
> >variables to do the looping then there's no issue.
> 
> Never forget that you want to be able to debug you application.
> While technically you're right, it's bad practice to do so.

I disagree with this point. I think it's more error prone to rely on a
side effect of a loop variable to exist outside the scope of the loop.
I know that C programmers are used to this, but from the perspective
of good programming practice I don't think it's a good one.

Of these two situations:

Case 1:

int i;

for (i = 0; i < MAX; i++)
	if (i == 5) break;

printf("Found %dth element\n");


Case 2:

int fifth_element = 0;

for (int i = 0; i < MAX; i++)
	if (i == 5) {
		fifth_element = i;
		break;
	}
}

if (fifth_element)
	printf("Found %dth element", fifth_elemtn);


The latter seems the better written code to me. It's more verbose, but
it's clearer what's being done. It seems pointless when you consider
it in isolation but since probably more than 99% of for loops only
declare outer scope variables in order to terminate the loop the above
is the exception and not the rule and for the other 99% of the time
using localised looping variables is better since it doesn't pollute
the outer scope.

-- 
Paul Richards



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20050201204331.GH61409>