Main Content

MISRA C++:2008 Rule 16-0-8

If the # token appears as the first token on a line, then it shall be immediately followed by a preprocessing token

Description

Rule Definition

If the # token appears as the first token on a line, then it shall be immediately followed by a preprocessing token.

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 be malformed.

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 malformed, the compiler continues excluding code beyond the intended end point, resulting in bugs and unexpected behavior which can be difficult to diagnose.

Avoid malformed 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 is not a preprocessor directive and follows directly after the # character, Polyspace flags it as noncompliant.

#endnif is not a properly formed preprocessor directive. Polyspace flags it as noncompliant.

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

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2013b