Main Content

MISRA C:2012 Rule 20.4

A macro shall not be defined with the same name as a keyword

Description

Rule Definition

A macro shall not be defined with the same name as a keyword.

Rationale

Using macros to change the meaning of keywords can be confusing. The behavior is undefined if you include a standard header while a macro is defined with the same name as a keyword.

Additional Message in Report

  • The macro macro_name shall not be redefined.

  • The macro macro_name shall not be undefined.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <stdlib.h>
#define int some_other_type /* Non-compliant - int keyword behavior altered */
           
//...

In this example, the #define violates Rule 20.4 because it alters the behavior of the int keyword. The inclusion of the standard header results in undefined behavior.

Correction — Rename keyword

One possible correction is to use a different keyword:

#include <stdlib.h>
#define int_mine some_other_type

//...
#define while(E) for ( ; (E) ; )  /* Non-compliant - while redefined*/
#define unless(E) if ( !(E) )     /* Compliant*/

#define seq(S1, S2) do{ S1; S2;} while(false)  /* Compliant*/
#define compound(S) {S;}                       /* Compliant*/
//...

In this example, it is noncompliant to redefine the keyword while, but it is compliant to define a macro that expands to statements.

#define inline // Non-compliant 

In this example, redefining inline is compliant in C90, but not in C99 because inline is not a keyword in C90.

Check Information

Group: Preprocessing Directives
Category: Required
AGC Category: Required