[Solved] Reasons four double undescores in standard library implementations


There is a good reason for the standard library to start internal names with two underscores: Such names are reserved for the implementation.

Imagine you write the following code:

#include <iostream>

using namespace std;

long square(long x)
{
  return x*x;
}

int main()
{
  cout << square(3) << endl;
}

I guess you would not be happy if this ended up calling some internal function square(int) used in implementing the standard library and doing something completely different, because it’s a better match than your square(long) for square(3).

By prefixing all internal names with double underscores and at the same time the standard declaring that you are not allowed to do the same, the standard library authors ensure that something like this cannot happen.

Now you may say that <iostream> is not part of the STL, but every standard library header may include any other standard library header, so iostream may well include an STL header for use in its implementation.

Another reason why identifiers with double underscores make sense even in the case of local identifiers that are not seen externally is that you might have defined a macro of the same name. Consider:

#define value 15

#include <iostream>

int main()
{
  std::cout << value;
}

This is legal code and certainly should output 15. But now imagine what happened if some object in iostream declared a local variable names value. Your code obviously wouldn’t compile.

Note that the standard library is part of the implementation (it’s described in the C++ standard, after all), so it can use reserved names however it likes.

9

solved Reasons four double undescores in standard library implementations