// main.cpp
const double MAX = 3.5;
namespace ns
{
const int MAX = 3;
}
int main()
{
}
will this cause redefinition error?
I'm referring to this MSDN page, which says in the Remarks section that this is an error.
Update: I think I may miss one important statement when copying around the code.
using ns::MAX;
No - I don't see how that code would cause a redefinition error.
And in fact, you can compile it and see for yourself.
EDIT: Following up now that you've supplied the link to the MSDN page you mentioned...
That MSDN page is talking about name clashes in the context of a using directive:
If a local variable has the same name as a namespace variable, the namespace variable is hidden. It is an error to have a namespace variable with the same name as a global variable.
Here's an example of a local variable hiding a namespace variable that's been brought into scope by a using directive:
namespace ns
{
const int MAX = 3;
}
using namespace ns;
int main()
{
int MAX = 4; // local
int test = MAX; // test is 4, because the local variable is used
// as the namespace variable is hidden
}
The inclusion of the using directive brings all of the names declared within the ns namespace into scope. However, when I assign the value of MAX to test, it's the local variable MAX that is used in the assignment because the namespace variable MAX is hidden. The local variable takes precedence and hides the namespace variable.
Now here's an example of a clash between a namespace variable and a global variable. Consider this amended piece of code (and you can see it compile here):
const double MAX = 3.5;
namespace ns
{
const int MAX = 3;
}
using namespace ns;
int main()
{
int test = MAX;
}
Again, the using directive brings ns:MAX into scope, and the global variable MAX is also in scope.
When I go to use the variable called MAX in main(), the compiler reports an error because the name MAX is now ambiguous: it has no way of knowing which MAX we are referring to, as there are two non-local MAXs to choose from: neither has any precedence.
prog.cpp: In function ‘int main()’:
prog.cpp:13: error: reference to ‘MAX’ is ambiguous
prog.cpp:2: error: candidates are: const double MAX
prog.cpp:6: error: const int ns::MAX
prog.cpp:13: error: reference to ‘MAX’ is ambiguous
prog.cpp:2: error: candidates are: const double MAX
prog.cpp:6: error: const int ns::MAX
They wouldn't because one is in file scope and the other in namespace scope.
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