Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 31 Jan 2005 17:04:17 +0000
From:      Paul Richards <paul@originative.co.uk>
To:        Ulrich Spoerlein <q@uni.de>
Cc:        Poul-Henning Kamp <phk@phk.freebsd.dk>
Subject:   Re: c99/c++ localised variable definition
Message-ID:  <20050131170417.GW61409@myrddin.originative.co.uk>
In-Reply-To: <20050131165817.GV61409@myrddin.originative.co.uk>
References:  <20050131122609.GA83556@gurney.reilly.home> <90392.1107174969@critter.freebsd.dk> <20050131163117.GE828@galgenberg.net> <20050131165817.GV61409@myrddin.originative.co.uk>

next in thread | previous in thread | raw e-mail | index | archive | help
On Mon, Jan 31, 2005 at 04:58:17PM +0000, Paul Richards wrote:
> On Mon, Jan 31, 2005 at 05:31:17PM +0100, Ulrich Spoerlein wrote:
> > On Mon, 31.01.2005 at 13:36:09 +0100, Poul-Henning Kamp wrote:
> > > >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.
> > > 
> > > I would _really_ hope we have the compiler warning about this
> > > already ?
> > 
> > Doesn't look so:
> > #include <stdlib.h>
> > #include <stdio.h>
> > 
> > int
> > main(int argc, char **argv) {
> >   int N = 42;
> >   int i;
> >   for (int i = 0; i < N; i++)
> >     if (i == 23)
> >       break;
> >   printf("%d\n", i);   /* use finishing index */
> >   return (0);
> > }
> > 
> > % cc -Wall -std=c99 test.c && ./a.out
> > 1
> 
> gcc should be throwing an uninitialised warning here.

With the right warns it does :-)

cc -Wall -std=c99 -O -Wuninitialized test.c
test.c
test.c: In function `main':
test.c:7: warning: 'i' might be used uninitialized in this function

-- 
Paul Richards



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