sivakrdy
sivakrdy

Reputation: 51

"does not name a type" error when using namespaces in c++

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;
}

Upvotes: 5

Views: 1551

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

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.

Upvotes: 10

Related Questions