Accessing a global variables within nested namespaces

Viewed 209

I am quite new to c++ and having trouble with namespaces.

#include <iostream>

int x = 10;

namespace ns {
    int x = 5;

    namespace ns_nested {
        int z = x;  //z is assigned a value of 5??
    }
}


int main(){
    std::cout << ns::ns_nested::z;
}

This prints 5. Initially, I thought this was because I was just changing the value of x to 5 from 10.

But if I change the first declaration of x to const int x = 10, it still prints 5.

So, my question here is twofold:

  1. I though the variables declared in a global scope was... well... global, as in just one instance of it was available to all. So, why/how am I able to declare an instance of a variable with the same name again?

  2. If I were to assign the value of z to the value of x that was declared globally instead of the one in the outer namespace, how would I do it?

1 Answers

1) I though the variables declared in a global scope was... well... global, as in just one instance of it was available to all. So, why/how am I able to declare an instance of a variable with the same name again?

  namespace ns {
    int x = 5;

    namespace ns_nested {
        int z = x;  //z is assigned a value of 5??
    }
 }

here x is not global namespace it is under namespace ns

2)If I were to assign the value of z to the value of x that was declared globally instead of the one in the outer namespace, how would I do it?

see this you may got an idea

#include <iostream>

const int x = 10;

namespace ns
{
    int x = 5;

    namespace ns_nested
    {
        int z1 = ::x;    //global namespace
        int z2 = ns::x;  //ns namespace
    }
}


int main()
{
    std::cout << ns::ns_nested::z1<<std::endl;
    std::cout << ns::ns_nested::z2<<std::endl;
}
Related