In C++ we have two similar mechanisms to limit the scope of a variable to the current code file (not header):
//fichero.cpp
// opción 1
static std::string Mensaje = "algo";
// opción 2
namespace
{
std::string Mensaje = "algo";
}
Is there a difference between both options? Which should be used? Why?
Today, for the example you mention (that is, for a case in which
static
it is not used to declare member variables, and discarding its use when declaring or implementing classes or functions), they serve to do exactly the same thing, which is to limit the use of those variables only from the file in which they are declared.At some point the committee
C++
decided to disapprove ("deprecate") the use ofstatic
, leaving the use ofnamespaces
nameless as the only option officially accepted as good practice. This is no longer the case , and now they both serve the same purpose and are accepted. The reason was that it would simply be hard to conceive of this usagestatic
being removed fromC++
, especially considering one of its goals is compatibility withC
.Now... the most obvious difference is that by using the
namespace
you save writingstatic
for each variable. It could be said that it is more in line with the philosophy ofC++
.In the end, the decision is yours, but I add other observations that can help you:
static
might become more familiar to other people reading the code, especially if those people knowC
, but don'tC++
.static
has other uses and this could become confusing. For example, its use within a function, where any variable declared with this word will be initialized only once in the entire program, and its value will persist between function calls; that is, if you initialize the variable to 0, but at the end of the function the value of the variablestatic
is 1, when you call the function again the value of that variable will be 1, not 0. If you want to avoid problems with this, consider usingnamespace
, but this can also have its problems with other uses of the wordnamespace
and confuse readers of your code.Personally, I would use
static
, because I learned firstC
and never remember to usenamespace
it that way.