Main Content

MISRA C++:2023 Rule 19.0.1

A line whose first token is # shall be a valid preprocessing directive

Since R2024b

Description

Rule Definition

A line whose first token is # shall be a valid preprocessing directive.

Rationale

The # character precedes a preprocessor directive when it is the first character on a line. If the # character is not immediately followed by a preprocessor directive, the preprocessor directive might not be valid.

Preprocessor directives might be used to exclude portions of code from compilation. The compiler excludes code until it encounters an #else, #elif, or #endif preprocessor directive. If one of those preprocessor directives is not valid, the compiler continues excluding code beyond the intended end point, resulting in bugs and unexpected behavior which can be difficult to diagnose.

Avoid invalid preprocessor directives by placing the preprocessor token directly after a # token. Specifically, do not place any characters other than white space between the # token and preprocessor token in #else and #endif directives.

Polyspace Implementation

Polyspace® raises this defect when the # character is followed by any character that is not part of a properly formed preprocessor token. A preprocessor token that is preceded or followed by any character other than white space causes Polyspace to raise this defect. Polyspace raises this defect when a preprocessor token is badly formed due to misspelling or improper capitalization.

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

#define TESTING_H       //Compliant

namespace Example
{
#ifndef TESTING_H       //Compliant
    // code here
#elseX;                 //Noncompliant
    // code here
#else;                  //Compliant
    // code here
#endnif                 //Noncompliant
    // code here
  }

};

Because elseX and #endnif are not valid preprocessor directives , Polyspace reports a violation of this rule on these directives.

#define TESTING_H, #ifndef TESTING_H, and #else are valid preprocessor conditionals and are compliant with this rule.

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2024b