How anonymous namespaces avoids making global static variable?

We can have anonymous namespaces (namespace with no name). They are directly usable in the same program and are used for declaring unique identifiers. It is said that it avoids making global static variable.My question is if it is not static then why default value is zero?

As these question has been asked before but it is not clear at all C++ anonymous namespace: Variables initialized to 0?

#include<iostream>
using namespace std;

namespace 
{
  int x; // Here x should have garbage value according to definition of anonymous namespace
}

int main()
{
   cout << x << endl;// But x is throwing zero why?
}

I think you incorrectly understand the phrase

It is said that it avoids making global static variable

or the phrase itself is confusing.

In this phrase word static means internal linkage. For example if you will write

namespace N // named namespace
{
   static int x;
}

then variable x will have internal linkage. it will not be visible outside the compilation unit where it is defined. Or each module that will contain this definition will have a separate object with name x.

To achieve the same effect you could place its definition in an unnamed namespace. In this case according to the C++ 2011 Standard it will also have the internal linkage.

namespace // unnamed namespace
{
   int x;
}

At the same time any object defined in a namespace has static storage duration. It means that it will be initialized. For fundamental scalar types the initialization is the zero initialization.


The anonymous namespace doesn't really prevent names from becoming global names! In fact, a compiler may create object files which define the symbols as global symbols. However, the anonymous namespace basically hides these global names away with a name which can only be referred to from one translation unit.

The zero initialization applies to all objects with static storage duration. All variables at namespace level, including the anonymous namespace and function local static variable have static storage duration unless they are declared thread_local .

链接地址: http://www.djcxy.com/p/35326.html

上一篇: 如何从另一个名称空间定义函数和数据,而不是全局名称空间?

下一篇: 匿名命名空间如何避免使全局静态变量?