I have read on static variables and know what they are, how they function when define in a .cpp file, function, and class.
But I have slight confusion when define in different namespaces in the same cpp file.
One of these voted answers here says:
When you declare a variable as static inside a .h file (within or without namespace; doesn't matter), and include that header file in various .cpp files, the static variable becomes locally scoped to each of the .cpp files.
According to the program below, namespaces does matter.
static int a = 0;
namespace hello1 {
static int a = 1;
namespace hello2 { static int a = 2;}
namespace hello3 { static int a = 3;}
}
int main()
{
std::cout<<::a<<hello1::a<<hello1::hello2::a<<hello1::hello3::a;
return 0;
}
output
0123
Here is what I think: a
outside namespaces is the file scope. a
in hello1 is hello1 scope. Since hello1 is global scope namespace, I can only have one a
in namespace hello1, including other cpp files where hello1 exists. The same goes for hello2 and hello3; only one a
in each hello1::hello2 and hello1::hello3.
Please correct me If I understood it correct. The namespace does matter; static variables in the same cpp file under different namespaces are different entities.