David Mathog said:
Quote:
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:
Quote:
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>
Quote:
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!).
Quote:
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.
Quote:
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@heregcc -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