Main Content

MISRA C++:2023 Rule 19.1.3

All identifiers used in the controlling expression of #if or #elif preprocessing directives shall be defined prior to evaluation

Since R2024b

Description

Rule Definition

All identifiers used in the controlling expression of #if or #elif preprocessing directives shall be defined prior to evaluation.

Rationale

If you attempt to use a macro identifier in a preprocessing directive, and you have not defined that identifier, then the preprocessor assumes that it has a value of zero. This value might not meet developer expectations.

Polyspace Implementation

Polyspace® flags an #if or #elif statement if it uses an undefined macro identifier.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#if M == 0           //Noncompliant
#endif

#if defined (M)      //Complaint
#if M == 0           //Executes only when M is defined
#endif
#endif

#if defined (M) && (M == 0)  //Compliant
//...
#endif

#define XXYY 1                                          
#define ADD(a,b) a##b                                   

#if ADD(XX,YY)  // Compliant                                        
#endif

This example shows various uses of M in preprocessing directives:

  • The first #if clause uses the undefined identifier M. Because M is undefined when this preprocessor directive is evaluated, the compiler assumes that M is zero, which results in unexpected results. Such a use of undefined identifiers is not compliant with this rule. Polyspace flags the #if statement.

  • The second and third #if statements use the undefined identifier M as the operand to the defined operator. These use of undefined identifiers are compliant with this rule.

  • The final #if statement uses the result of the macro ADD(). The macro resolves to the token XXYY, which is defined. Polyspace does not report a violation.

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2024b