namespace myspace { int x } Now why `myspace::x=3;` gives error?

Viewed 123

Code

#include <iostream>
namespace myspace
{
    int x;
}

myspace::x=3; // This line is giving error.
int main()
{
    myspace::x=5;
    return 0;
}

Output

Error: C++ requires a type specifier for all declarations

So why line myspace::x=3; giving error that C++ requires a type specifier for all declarations ?

2 Answers

The statement

myspace::x=3;

isn't an initialization, it's a plain assignment. It's no different from the

myspace::x=5;

you have inside the main function.

Any statement that isn't a declaration or a definition can't be outside functions.

If you want to initialize the variable, do it at the definition:

namespace myspace
{
    int x = 3;
}

You provided a definition upon first declaring the variable. And as others noted myspace::x=3; constitutes an assignment expression at namespace scope, which is not allowed.

If you want to declare the variable without defining it, you need to be explicit and specify it's an extern declaration.

namespace myspace
{
    extern int x;
}

The definition would still need the type specifier (as all definitions do), but it will look somewhat like what you imagined

int myspace::x = 3;

While all of this is fine and dandy, global variables (the mutable, run-time external kind) are a code smell. So best not to get in the habit of using them.

Related