2

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?

Mubin
  • 130
  • 1
  • 9
  • In `int z = x;` `x` is being searched down the namespace hierarcy: first `::ns::ns_nested::x`, then `::ns::x` and then `::x`, `::ns::x` and `::x` are not the same. – fas Mar 30 '20 at 06:17
  • One of the reasons to use namsespaces is so that different things can have the same name. I can make my own `sort` function and it will not collide with the standard sort since they are name `std::sort` and `my::sort`. Here you have `::x` and `ns::x`. – super Mar 30 '20 at 06:21
  • @Mubin - _So, why/how am I able to declare an instance of a variable with the same name again?_ - Would you wonder the same for `int x = 10; void fn() { int x = 5; }`? – Armali Mar 30 '20 at 06:22
  • Does this answer your question? [Nested NameSpaces in C++](https://stackoverflow.com/questions/3199139/nested-namespaces-in-c) – fas Mar 30 '20 at 06:25
  • Answer to 2: `namespace ns_nested { int z = ::x; } //z is assigned a value of 10` – mcabreb Mar 30 '20 at 06:37
  • 1
    @Armali yes, actually. – Mubin Mar 30 '20 at 06:45
  • @user3365922 and mcabreb thanks. that explans the answer to my second question – Mubin Mar 30 '20 at 06:46

1 Answers1

2

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;
}
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25