Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Why is an unnamed namespace used instead of static?

namespace static unnamed Used
0
Posted

Why is an unnamed namespace used instead of static?

0

In C++, some uses of the static keyword have been deprecated. In particular, an unnamed namespace should be favored over some previous uses of “file scope static’s”. In fact in some cases an unnamed namespace must be used in order to obtain a similar effect. That is to say, this code: // x.cpp static bool flag = false; // AAA void foo() { if (flag)… } void bar() { …flag = true… } should instead often be composed this way in C++: // x.cpp namespace /* NOTHING HERE!! */ { // BBB bool flag = false; // no need for static here } The use of static in AAA indicates that flag has internal linkage. This means that flag is local to its translation unit (that is, effectively it is only known by its name in some source file, in this case x.cpp). This means that flag can’t be used by another translation unit (by its name at least). The goal is to have less global/cross-file name pollution in your programs while at the same time achieving some level of encapsulation. Such a goal is usually con

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.