Main Content

MISRA C++:2023 Rule 19.1.2

All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are related

Since R2024b

Description

Rule Definition

All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are related.

Rationale

You use preprocessor directives, such as #if...#elif...#else...#endif, to conditionally include or exclude blocks of code. If the different branches of such a directive reside in different source files, the code can be confusing. If all the branches are not included in a project, the code might behave in unexpected ways. To avoid confusion and unexpected behavior, keep the branches of a conditional preprocessor directive within the same source file.

Polyspace Implementation

Polyspace® raises a violation of this rule if either of these conditions are true:

  • A corresponding #if directive cannot be found within a source file for every #else, #elif, or #endif directive.

  • A corresponding #endif directive cannot be found within a source file for every #if directive.

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

//file1.h
#if !defined (FILE)
//.....
#elif               // Noncompliant
//...///
//file2.h
#else              // Noncompliant
//...
#endif             // Noncompliant
///

In this example, a conditional directive is split across two source files.

  • In file1.h, the #if directive has no corresponding #endif directive. Polyspace flags the block.

  • In file2.h, the #else and #endif directives have no corresponding #if directive. Polyspace flags both directives.

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2024b