Re: Question about variable scope conflict
- From: santosh <santosh.k83@xxxxxxxxx>
- Date: Fri, 30 Nov 2007 22:57:19 +0530
David Mathog wrote:
I accidentally did this the other day (it was a lot less obvious in
the much longer actual program, hundreds of lines are omitted):
----------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
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;
/* much code, including a qsort where the compare function
needed the value of gbl_var, but read 0 instead of 1.
Here just call compare directly */
compare();
exit(EXIT_SUCCESS);
}
-----------------------------------------------------------
% gcc -Wall -std=c99 -pedantic -o foo foo.c
% #no warnings or errors are reported
% ./foo
gbl_var is 0
------------------------------------------------------------
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? 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. Still, it would have been nice if the compiler could have at
least
optionally warned about this.
Use the -Wshadow switch for gcc.
.
- Follow-Ups:
- Re: Question about variable scope conflict
- From: David Mathog
- Re: Question about variable scope conflict
- References:
- Question about variable scope conflict
- From: David Mathog
- Question about variable scope conflict
- Prev by Date: Re: Global Variables : Where are they stored ?
- Next by Date: Re: Global Variables : Where are they stored ?
- Previous by thread: Question about variable scope conflict
- Next by thread: Re: Question about variable scope conflict
- Index(es):
Relevant Pages
|