c99/c++ localised variable definition

Ulrich Spoerlein q at uni.de
Mon Jan 31 08:31:27 PST 2005


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
% icc -Wall -std=c99 test.c && ./a.out
test.c(12): remark #592: variable "i" is used before its value is set
    printf("%d\n", i);   /* use finishing index */
                   ^
0

But the ICC warning is bogus too, if you happen to set i before, the
warning disappears.

Ulrich Spoerlein
-- 
 PGP Key ID: F0DB9F44				Encrypted mail welcome!
Fingerprint: F1CE D062 0CA9 ADE3 349B  2FE8 980A C6B5 F0DB 9F44
Ok, which part of "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn."
didn't you understand?


More information about the freebsd-arch mailing list