I've inherited some code which I'm going to be refactoring that makes extensive use of multiple variables at different scopes having the same name, ie:
int test = 456;
int main(void) {
int test = 0;
//...
for (i=0; i<MAX_VAL; i++) {
int test = 123;
//...
}
return 0;
}
I know that if the same variable name is only used at two relevant levels of scope, I can access the globally accessible one by declaring extern int test
within the deeper/lower levels of scope. With more than two levels though, I'm not sure which test
variable is being accessed: the global scope variable or the variable at one scope level higher.
I've decided to re-write the code to use different variable names, and in doing so, have uncovered a lot of bugs that have been hard to track in the past. Is there a way to trigger a warning when such behavior is used? I have to compile the code in both Linux via GCC and Windows via Visual Studio 2010. If a portable approach isn't possible, is there a way for each of these compilers to warn about multiple variables at different scopes with the same name? This would let me build the code and have a list of all locations where such behavior is used.
Thank you.