This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 19.0.1
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
This rule applies to all the lines within a translation unit, even if they are excluded by preprocessing.
Note: white-space is permitted before and after the #
token.
Rationale
A preprocessor directive may be used to conditionally exclude source code until a corresponding #else
, #elif
or
#endif
directive is encountered. A malformed or invalid preprocessing directive contained within the excluded source code may not be
detected by the compiler, possibly leading to the exclusion of more code than was intended.
Requiring all preprocessor directives to be syntactically valid, even when they occur within an excluded block of code, ensures that this cannot
happen.
Example
In the following example all the code between the #ifndef
and #endif
directives may be excluded if AAA
is
defined. The developer intended that AAA
be assigned to x
, but the #else
directive was entered incorrectly and
not diagnosed by the compiler.
#define AAA 2
int32_t foo()
{
int32_t x = 0;
#ifndef AAA
x = 1;
#else1 // Non-compliant
x = AAA;
#endif
return x;
}
This rule does not apply to the following examples as the #
is not a preprocessing token:
// Not a preprocessing token within a comment \
#not a token
auto s = R"(
#text)"; // Use in a raw string literal is not a preprocessing token
Copyright The MISRA Consortium Limited © 2023