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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With