Re: Question about variable scope conflict



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.


.



Relevant Pages

  • Question about variable scope conflict
    ... void compare{ ... including a qsort where the compare function ... % #no warnings or errors are reported ... it would have been nice if the compiler could have at least optionally warned about this. ...
    (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)
  • 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.cpp)
  • Re: Tcl 8.5 HP/UX Compiler warnings
    ... results and "the optional HP ANSI C compiler", ... stat64 struct pointers are being ... The elementary types of the structure ... other warnings I cited are similarly harmless. ...
    (comp.lang.tcl)
  • Re: Is it standard and practical to use long long types?
    ... right option for putting the compiler in conforming mode. ... Bogus/idiotic warnings when all warnings are enabled. ... For reference, this what I get from gcc, when invoked in conforming mode ...
    (comp.lang.cpp)