Is the # undef'ing keyword illegal?

I expected the following program to emit diagnostics in GCC or Clang:

#undef protected
#undef private

      

because of [macro.names] / 2:

The translation unit should not be #define

either #undef

names lexically identical to the keywords, identifiers listed in Table 3, or the attribute tokens described in 7.6.

protected

and private

are listed in Table 3. A quick "no diagnostic" search through the N3337 found nothing. So should compilers complain in this case?

+3


source to share


3 answers


[macro.names] is part of [reserved.names] which says that "If a program declares or defines a name in the context where it is reserved, other than explicitly allowing this condition, its behavior is undefined." So this behavior is undefined. ...

In practice, most compilers will not complain for two reasons: first, because preprocessing is usually done before the compiler evaluates whether a character is a keyword or not; this is an earlier phase of translation. And also because such declarations are illegal if you are actually using the standard library (although other libraries such as Posix or Windows can and probably enforce similar rules).

EDIT:



Just a general comment: while there is no global statement for this in the standard, there is a general, underlying principle that violation of library constraints is undefined behavior; the intention is that the compiler doesn't need to know anything about the library, and that the implementation can treat #include <vector>

it exactly the same way #include "MyHeader.hpp"

(except perhaps where it looks for the file). And the restrictions stated in the original publication are restrictions on programs using the library, and apply only to such programs. Something like:

#define while if
int
main( int argc, char** argv )
{
    int retval = 0;
    while ( argc > 0 ) {
        ++ retval;
        -- argc;
    }
    return retval;
}

      

is a well-defined and legal C ++ (and C) program guaranteed by return 1. (Of course, I wouldn't recommend anything like that.)

+6


source


Yes, but in practice most do not. Klang received a warning recently.



0


source


Of course, it's not a good idea to use names that are reserved for keywords. However, most compilers will not warn you about this.

You can look at overriding keywords in C / C ++ .

It's on similar lines.

0


source







All Articles