namespace without name. I do not understand

Why would I write a namespace without name:

namespace
{
double d = 88.22;
}

And not directly:

double d=88.22;

Both are considered definitions of global variables...
Last edited on
This is known as an "anonymous namespace".

From outside the file, the objects inside the anonymous namespace are invisible. This is a way to restrict visibility to one file.
In other words, d will have internal linkage.

namespace { double d = 88.22; } is essentially the same as static double d = 88.22;
Last edited on
if it helps, I have never felt compelled to do this. I personally name all my namespaces, structs, classes, and enums etc. and have found nameless stuff to be more annoying than useful in general. I don't really like the namelessness of lambdas either, but its going to be hard to avoid those going forward I think.
Last edited on
I have found nameless things to be very useful in situations where I don't want any other parts of the codebase to use them. Horses for courses.
closed account (z05DSL3A)
Peter87 wrote:
In other words, d will have internal linkage.

Doesn't it still have external linkage, just looks like internal linkage due to the anonymous namespace actually having a hidden unique name?
No, the standard says it has internal linkage.

http://eel.is/c%2B%2Bdraft/basic.link#6
closed account (z05DSL3A)
Okay, I was getting confused by a footnote attached to the section on unnamed namespace...
Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit
.
Topic archived. No new replies allowed.