Friday, July 17, 2009

Episode Two: Those Whose Names must not be Spoken

The C++ standard reserves a set of names for use by C++ implementation and standard libraries [C++ standard 17.6.3.3 - Reserved names]. Those include but are not limited to:

- Names containing a double underscore.
- Names that begin with an underscore followed by an uppercase letter.
- Names that begin with an underscore at the global namespace.



The standard itself makes use of such reserved names in macros like __FILE__ and __LINE__ as well as the new (C++0x) local variable __func__.

The C standard has even stricter rules for reserved function and macro names for future implementation. C functions live at the global namespace; staying out of it is a good practice to avoid name clashing. Macro names must be selected with special care, since they do not respect scopes.

Is not uncommon to see source code that makes use of these reserved names. This is specially seen at scope guards in the form _FILENAME_H_. Such usage can only be attributed to unawareness of the standard, but nonetheless results in undefined behavior.

Most of the time, those names can be used and still get away with it. For instance, MSVC8 does not seem to have a problem to handle a member object named `__vfptr` in a class with virtual functions, even though `__vfptr` is the name for the implicitly defined virtual function table. However, the compiler is allowed to reject the code, or even worse do whatever it wants with it.

Fortunately, staying in the safe zone is just as easy as avoiding reserved names.

No comments:

Post a Comment