Re: Question about variable scope conflict
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Fri, 30 Nov 2007 18:42:54 +0000
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 */<snip>
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;
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
.
- Follow-Ups:
- Re: Question about variable scope conflict
- From: dj3vande
- Re: Question about variable scope conflict
- References:
- Question about variable scope conflict
- From: David Mathog
- Question about variable scope conflict
- Prev by Date: Re: Question about variable scope conflict
- Next by Date: bus error
- Previous by thread: Re: Question about variable scope conflict
- Next by thread: Re: Question about variable scope conflict
- Index(es):
Relevant Pages
|