C++ preprocessor #define-ing a keyword. Is it standards conforming?

Help settle the debate that's going on in the comments at this question about bool and 1:

Can a standards-conforming C++ preprocessor allow one to use #define to redefine a language keyword? If so, must a standards-conforming C++ preprocessor allow this?

If a C++ program redefines a language keyword, can that program itself be standards conforming?


Solution 1:

In C++, the closest thing to forbidding #defineing a keyword is §17.4.3.1.1/2, which only disallows it in a translation unit that includes a standard library header:

A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translation unit define macros for names lexically identical to keywords.

The second sentence of that paragraph has been changed in C++0x to outright forbid #defineing a keyword (C++0x FCD §17.6.3.3.1):

A translation unit shall not #define or #undef names lexically identical to keywords.

Edit: As pointed out by Ken Bloom in comments to his answer, the rules have not changed in C++0x; the text has just been rearranged to confuse people like me. :-)

Solution 2:

Working from the 2005-10-19 C++ working draft (since I don't have a standard handy):

Section 16.3 defines the grammar for #define to be #define identifier replacement-list-newline (object-like macros) or one of several constructions beginning with #define identifier lparen (function-like macros). identifiers are defined in section 2.10 to be identifier-nondigit | identifier identifier-nondigit | identifier digit. Section 2.11 indicates that a certain list of identifiers are unconditionally treated as keywords in phase 7 of compilation (section 2.1), and I conclude that they are therefore not treated specially in phase 4, which is preprocessor expansion. Thus, it appears that the standard requires the preprocessor to allow you to redefine language keywords (listed in Section 2.11).

However, the preprocessor has a keyword of its own, namely defined, as well as a list of predefined macros (Section 16.8). Section 16.8 states that the behavior is undefined if you redefine these, but does not prohibit the preprocessor from recognizing these as macro names.

Solution 3:

It is not permitted, according to C++11 [macro.names]:

A translation unit shall not #define or #undef names lexically identical to keywords, to the identifiers listed in Table 3, or to the attribute-tokens described in 7.6.

The "identifiers listed in Table 3" are final and override; and the attribute-tokens are the identifiers in [[fallthrough]] and so on.

This clause is still in the latest standard too.