Question about variable scope conflict



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
.



Relevant Pages

  • Re: Question about variable scope conflict
    ... including a qsort where the compare function ... % #no warnings or errors are reported ... Once I found the bug I was a bit surprised that the compiler had not ...
    (comp.lang.c)
  • Re: Type-casting void pointers?
    ... >> delivering code with hundreds of warnings is not good for business). ... You mean assigning void* to a pointer to non-void? ... used (could have been the IAR H8 series compiler, ...
    (comp.lang.c)
  • Re: Is this program standard conform?
    ... void xfprintf{ ... It compiles with gcc without warnings and works correctly, ... Error xfprintf.c: 4 redefinition of 'xfprintf' ... my program or the compiler? ...
    (comp.lang.c)
  • Re: Is this program standard conform?
    ... void xfprintf{ ... It compiles with gcc without warnings and works correctly, ... Error xfprintf.c: 4 redefinition of 'xfprintf' ... my program or the compiler? ...
    (comp.lang.c)
  • Re: Is it standard and practical to use long long types?
    ... > right option for putting the compiler in conforming mode. ... > compiler is invoked with the extensions disabled, ... Bogus/idiotic warnings when all warnings are enabled. ... GCC does not fully support C99, yet ansi invokes it's C99 spirit. ...
    (comp.lang.c)