Re: Question about variable scope conflict



David Mathog said:

I accidentally did this the other day (it was a lot less obvious in the
much longer actual program, hundreds of lines are omitted):

I'll trim a little more out for you:

int gbl_var=0; /* one of several globals */

void compare(void){
(void) fprintf(stdout,"gbl_var is %d\n",gbl_var);
}

int main(void){
int gbl_var; /* <----- OOPS, left over from a previous version */
gbl_var=1;
<snip>

Once I found the bug I was a bit surprised that the compiler had not
issued a warning. What does the standard say about using the same
variable name in two overlapping scopes like this?

It's perfectly legal, and the effect you noticed is conforming. The inner
scope's declaration takes precedence (if that's the right word!).

Apparently it allows
it, I guess to avoid accidental name conflicts, for instance between a
global in a library and a similarly named variable in a function.

Presumably, yes - but it's Yet Another Good Reason to minimise or even
eliminate your use of file scope objects.

Still, it would have been nice if the compiler could have at least
optionally warned about this.

You seem to be using gcc, so try the -Wshadow switch; here's what it does
with your code:

me@here> gcc -Wshadow -o foo foo.c
foo.c: In function `main':
foo.c:11: warning: declaration of `gbl_var' shadows global declaration

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.



Relevant Pages

  • Re: compiling error
    ... Kapteyn's Star said: ... The program here given is refused by GCC with a error i cannot ... void open_file ... int buf; ...
    (comp.lang.c)
  • Add "FORTIFY_SOURCE" to the linux kernel
    ... In recent Fedora Core and RHEL distributions, gcc and glibc have a feature ... +extern void __chk_fail; ... +#undef strncpy ...
    (Linux-Kernel)
  • Re: ProPolice/SSP in 7.0
    ... void overrun; ... int main ... or we have gcc misconfigured and it's not ... This is done by adding a guard variable to ...
    (FreeBSD-Security)
  • Re: data types
    ... Usually short is smaller than an int. ... Your compiler is either *really* old or broken or both. ... recommend either a version of gcc,, or Visual Studio ... Microsoft's Visual Studio Express has an onerous EULA). ...
    (comp.lang.c)
  • Re: stream io in c
    ... zero to 255, putchar'ing in the body of the loop, then redirecting output ... int main ... // gcc -o chars mkchars1.c ... This compiles but gcc warns of incompatible pointer types. ...
    (comp.lang.c)