Question about variable scope conflict
- From: David Mathog <mathog@xxxxxxxxxxx>
- Date: Fri, 30 Nov 2007 09:20:21 -0800
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. Unfortunately so far none of the -W
switches I've tried have flagged this problem, including -Wredundant-decls. Is there a "-Wvar-nested-scope" that I missed.
Regards,
David Mathog
.
- Follow-Ups:
- Re: Question about variable scope conflict
- From: Richard Heathfield
- Re: Question about variable scope conflict
- From: santosh
- Re: Question about variable scope conflict
- Prev by Date: C/C++ on UNIX Developer required in Woodmead, Johannesburg
- Next by Date: Re: Global Variables : Where are they stored ?
- Previous by thread: C/C++ on UNIX Developer required in Woodmead, Johannesburg
- Next by thread: Re: Question about variable scope conflict
- Index(es):
Relevant Pages
|