Given a structure such as below
class A {
int test;
void f() { int test; }
}
I just had a curious case in which the code in f(), when referring to test, compiled under VS2010, correctly referred to the function local variable, however, when compiled under gcc, incorrectly referred to the member variable. Took me quite a while to track down.
Anyway, question is, is there an option in gcc or VS to enable compiler warnings every time a member variable is re-declared in a local function scope?
In GCC,
-Wshadow
. From the documentation:I don't know if any such option exists.
But if it doesn't exist, then you can do the following. In fact, the naming convention is preferred even if there exists some compiler option to avoid the problem in the question, for it covers broader area of concerns:
That is, use some rules in naming the member variables, such as, prefix each with
m_
as inm_test
, Or use suffix as intest_
. This is the usual approach adopted by many programmers, and in many companies, there is similar rules which they impose when coding.Such naming conventions not only help avoiding the problem you came across, it also increases readability and maintainability, as the name
test
suggests nothing as to whether it is local variable or member variable in the absence of naming conventions. But once you adopt some naming conventions, such things become clear.