5

In the below code writing the statement A::x=5 is giving the error:

'x' in namespace 'A' does not name a type

Can't we assign a value globally for x variable?

#include <iostream>

int x = 10;  

namespace A
{
    int x = 20; 
}

A::x=5;

int main()
{
    int x = 30; 
    std::cout << "x = " << x << std::endl;
    std::cout << "A::x = " << A::x << std::endl;
    std::cout << "::x = " << ::x << std::endl;
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
sivakrdy
  • 51
  • 2
  • 2
    This has nothing to do with namespaces. The following (at global scope) would have the same problem `int x = 20; x = 5;` – john May 27 '20 at 08:22

1 Answers1

10

Can't we assign a value globally for x variable?

You can. But you must put the assignment statement into a function. e.g.

int main()
{
    A::x=5;
    int x = 30; 
    std::cout << "x = " << x << std::endl;
    std::cout << "A::x = " << A::x << std::endl;
    std::cout << "::x = " << ::x << std::endl;
}

Note that A::x=5; is a statement, but not definition (with initializer) like int x = 20;, they're different things.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405