Shadowing variables

In both C and C++ it is legal for the same name to be used within multiple scopes – some compilers (e.g. gcc -Wshadow) will provide a mechanism that warns you about this since it can cause confusion.

#include <iostream>

int i = 0;
int main() {
    int i = 1;
    for (int i = 0; i < 10; ++i) {
        int i = 2 * i;
        std::cout << i << std::endl;
    }
    return 0;
}

Some compilers will compile this and output ‘0, 2, 4, 6, 8, …’. Some won’t.

A common way to avoid this is to use prefixes. “m_” for “member”, “s_” for “static”, “g_” for “global”, etc. Some coding styles use a “_” suffix for member variables. This also helps to keep member variables from clashing with similarly named getters/setters if that’s the way your camel rolls.

class Measure {
    int         m_n;
    double      m_measureSet[MEASURE_SET_SIZE]; // [] is not legal in a class.
    std::string m_nomefile;
    double      m_t;

public:
    const std::string& nomefile() const { return m_nomefile; }
    ...
};

Where this pays off is in the usage, I tend to find developers are encouraged to use the accessors rather than the members (it seems to be easier to add () at the end than type “m_” at the beginning).

std::cout << "Measuring file " << nomefile << std::endl;

would become

std::cout << "Measuring file " << m_nomefile << std::endl;

or better:

std::cout << "Measuring file " << nomefile() << std::endl;

Leave a Comment