3
votes

Can i redefine keywords with #define in C?

I found this in C++ standards:

ISO/IEC 14882:1998 and ISO/IEC 14882:2003

17.4.3.1.1 Macro names [lib.macro.names]

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.

164) It is not permissible to remove a library macro definition by using the #undef directive.

ISO/IEC 14882:2011

17.6.4.3.1 Macro names [macro.names]

2 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.

So, we can't redefine keywords in C++98 / C++03 if we include any header files from Standard C++ Library, while in C++11 we can't do it in any translation unit, right?

3
What is the question? You have provided the quotes from the two standards that tell you that the program will be ill-formed if you do... what do you want to know? - David Rodríguez - dribeas
I want to know what C standard says about it - FrozenHeart
If you're only interested in what the C standard says, why not look it up? You've already found the appropriate sections of the C++ standard, there's a good chance the wording is similar in the C standard. - ssube
No, there isn't similar sections in C Standard - FrozenHeart
Not really constructive. - nikhil

3 Answers

3
votes

Can you? Yes, most compilers don't forcibly prevent it.

Should you? No, (almost) never, it's (usually) a horrible idea. All sorts of things may break, and as with most preprocessor nonsense, it's going to be very difficult to debug.

Therefore, can you legally? No.

In the same fashion, you can have macros or variables that start with __ or add things to the std:: namespace or all sorts of other Very Bad Things. However, most rules like this have Very Good Reasons (conflicts related to keywords or name resolution, mostly). While it may be physically possible, there are few (if any) times you need to and fewer still when you should.

2
votes

In C standard, it is not allowed.

C11, § 6.4.1 Keywords

[...]

The above tokens (case sensitive) are reserved (in translation phases 7 and 8) for use as keywords, and shall not be used otherwise.

1
votes

There are several aspects in this issue:

  • If you will redefine keywords, in 95% of compilers this will work fine regardless of what is written in the standards primarily because this was working in old compilers;
  • You can never be sure that this will work in the next version of your compiler;
  • You should avoid this from the practical stand point. The code will be more difficult to read and understand.

The bottom line: Do you really need this? What will you get?

p.s. I saw several times that try-catch were redefined in various headers.