Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can names inside an anonymous namespace in the global scope have leading underscores?

Tags:

c++

According to the spec, global names with leading underscores are not allowed:

17.4.3.1.2 Global names
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

Does this also apply for names defined in a top-level anonymous namespace?

like image 593
StackedCrooked Avatar asked Jan 01 '12 05:01

StackedCrooked


2 Answers

Names starting with a leading underscore followed by a non-capital alphanumeric character and not including a double underscore are only reserved in the global namespace. The reason for this is that on some systems certain names need to get a leading underscore or are already used by the underlying operating system and/or its C library. Names in an anonymous namespace don't have this problem.

That said, I'm always wondering why people are so keen to use ugly names! Unless I'm in standard library implementation mode (where I effectively have to use ugly names lest I conflict with user names) I'm always wondering if I'm doing something wrong using a leading underscore anywhere in my code! There are rare occasions where a leading underscore is needed (e.g. when calling _exit() or using std::bind()'s placeholders) but generally users shouldn't touch them: neither use nor define them.

like image 121
Dietmar Kühl Avatar answered Sep 22 '22 04:09

Dietmar Kühl


Yes. But that quote doesn't address that (as you know it yourself).

Here is what I think applies to that:

17.4.3.1.3 External linkage

3 . Each name having two consecutive underscores (2.11) is reserved to the implementation for use as a name with both extern "C" and extern "C++" linkage.

I think it applies to the variables declared with external linkage, in anonymous namespace, but it should be noted that it talks about double underscores. So:

namespace
{
   std::string __s1; //not allowed
   std::string _s2;  //allowed (allowed, as I understand)
}

A more general topic:

  • What are the rules about using an underscore in a C++ identifier?
like image 45
Nawaz Avatar answered Sep 23 '22 04:09

Nawaz