Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Macro replacement lists should be parenthesized to protect any lower-precedence operators from the surrounding expression. See also PRE00-C. Prefer inline or static functions to function-like macros and PRE01-C. Use parentheses within macros around parameter names.

Noncompliant Code Example

...

This compliant solution violates PRE00-C. Prefer inline or static functions to function-like macros. Consequently, this solution would be better implemented as an inline function.

...

In this example, the programmer has mistakenly omitted the comparison operator from the conditional statement, which should be getchar() != EOF. (See MSC02-C. Avoid errors of omission.) After macro expansion, the conditional expression is incorrectly evaluated as a binary operation: getchar()-1. This is syntactically correct, even though it is certainly not what the programmer intended. Note that this example also violates DCL00-C. Const-qualify immutable objects.

Parenthesizing the -1 in the declaration of EOF ensures that the macro expansion is evaluated correctly.

...

In this compliant solution, the macro definition is replaced with an enumeration constant in compliance with DCL00-C. Const-qualify immutable objects. In addition, since EOF is a reserved macro defined in the <stdio.h> header, the compliant solution must also use a different indentifier in order to comply with DCL37-C. Do not declare or define a reserved identifier.

Code Block
bgColor#ccccff
langc
enum { END_OF_FILE = -1 };
/* ... */
if (getchar() != END_OF_FILE) {
   /* ... */
}

...

ToolVersionCheckerDescription

LDRA tool suite

Include Page
LDRA_V
LDRA_V

77 S
78 S

Fully implemented

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

macrbody

Fully implemented
PRQA QA-C
Include Page
PRQA_V
PRQA_V
3409Fully implemented

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

PRE02-CPP. Macro replacement lists should be parenthesized
ISO/IEC PDTR 24772"JCW Operator precedence/order of evaluation" and "NMP Pre-processor directions"

Bibliography

...

]Section 6.10, "Preprocessing

...

Directives," and section 5.1.1, "Translation

...

Environment"

ISO/IEC PDTR 24772 "JCW Operator precedence/order of evaluation", "NMP Pre-processor directions"

Bibliography

[Plum 1985]Rule 1-1
[Summit 2005]Question 10.1