`Use variables in a named namespace instead of using external global variables.
`Use variables in an unnamed namespace instead of using static global variables.
when I am learning c++, i read these two sentences above, I cannot understand it well, so I come for asking help.
What does the two mean?
Any name declared outside any function is being declared in some namespace. If the namespace is not specified explicitly then it means that the name is declared in the global namespace. For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int x = 10; // x declared in the global namespace
namespace A
{
int x = 20; // x declared in namespace A
}
int main()
{
int x = 30; // local x
std::cout << "x = " << x << std::endl;
std::cout << "A::x = " << A::x << std::endl;
std::cout << "::x = " << ::x << std::endl;
}
With rare exceptions names declared in namespaces have external linkages.
According to the C++ 11 Standard names declared in unnamed namespaces have internal linkage that is they can be accessed only inside the translation unit where they are declared.
namespace
{
int x; //x can be accessed in this file only
}
Unnamed namespaces are preferred because a) Static keyword is deprecated when used to declare file scope
b) You can use them to define a class which can be used in curent file only (to hide implementation details for example) functions and whatever you want
vlad from moscow told about global variables in named namespaces already.
vlad, i have tried your way "extern int A::x;", but I get "namespace A has no member x". Do I need to put the "int x" into the header files? Now it's in another .cpp file, not .h file.
I find funny that no deprecated feature was ever deleted (except export which wasn't fully supported anyway) or changed meaning (aside from auto which nobody used) because of backward compatibility
I find funny that no deprecated feature was ever deleted (except export which wasn't fully supported anyway) or changed meaning (aside from auto which nobody used) because of backward compatibility
I think they deserve an applaud for being so brave to remove the implicit conversion to non-const char* for string literals.