Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to redefine a C++ keyword?

In this article from Guru of the week, it is said: It is illegal to #define a reserved word. Is this true? I can’t find anything in the norm, and I have already seen programmers redefining new, for instance.

like image 866
qdii Avatar asked Feb 02 '12 08:02

qdii


People also ask

Can keywords in C be changed?

Keywords cannot be used as variable names. Keywords have fixed meanings, and that meaning cannot be changed. They are the building block of a 'C' program. C supports 32 keywords.

Can a keyword be redefined?

You can't redefine keywords. However, you can specify text to replace keywords before compilation by using C preprocessor directives.


2 Answers

17.4.3.1.1 Macro names [lib.macro.names]

1 Each name defined as a macro in a header is reserved to the implementation for any use if the translation unit includes the header.164)
2 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.

By the way, new is an operator and it can be overloaded (replaced) by the user by providing its own version.

like image 149
Alok Save Avatar answered Sep 25 '22 20:09

Alok Save


They're actually wrong there, or at least doesn't tell the whole story about it. The real reason it's disallowed is that it violates the one-definition-rule (which by the way is also mentioned as the second reason why it's illegal).

To see that it's actually allowed (to redefine keywords), at least if you don't use the standard libraries, you have to look at an entirely different part of the standard, namely the translation phases. It says that the input is only decomposed into preprocessor tokens before preprocessing takes place and looking at those there's no distinction between private and fubar, they are both identifiers to the preprocessor. Later when the input is decomposed into token the replacement has already taken place.

It has been pointed out that there's a restriction on programs that are to use the standard libraries, but it's not evident that the example redefining private is doing that (as opposed to the "Person #4: The Language Lawyer" snippet which uses it for output to cout).

It's mentioned in the last example that the trick doesn't get trampled on by other translation units or tramples on other. With this in mind you should probably consider the possibility that the standard library is being used somewhere else which will put this restriction in effect.

like image 26
skyking Avatar answered Sep 24 '22 20:09

skyking