Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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;
}
like image 589
sivakrdy Avatar asked May 27 '20 08:05

sivakrdy


1 Answers

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.

like image 128
songyuanyao Avatar answered Nov 19 '22 08:11

songyuanyao