Preprocessor directive in macro argument
You use a preprocessor directive in the argument to a function-like macro
Description
This defect occurs when you use a preprocessor directive in the argument to a function-like macro or a function that might be implemented as a function-like macro.
For instance, a #ifdef
statement occurs in the argument to a
memcpy
function. The memcpy
function might be
implemented as a macro.
memcpy(dest, src, #ifdef PLATFORM1 12 #else 24 #endif );
printf
and assert
,
which can also be implemented as macros.Risk
During preprocessing, a function-like macro call is replaced by the macro body and
the parameters are replaced by the arguments to the macro call (argument
substitution). Suppose a macro min()
is defined as
follows.
#define min(X, Y) ((X) < (Y) ? (X) : (Y))
min(1,2)
, it is replaced by the body ((X) <
(Y) ? (X) : (Y))
. X
and Y
are
replaced by 1 and 2.According to the C11 Standard (Sec. 6.10.3), if the list of arguments to a function-like macro itself has preprocessing directives, the argument substitution during preprocessing is undefined.
Fix
To ensure that the argument substitution happens in an unambiguous manner, use the preprocessor directives outside the function-like macro.
For instance, to execute memcpy
with different arguments based
on a #ifdef
directive, call memcpy
multiple
times within the #ifdef
directive
branches.
#ifdef PLATFORM1 memcpy(dest, src, 12); #else memcpy(dest, src, 24); #endif
Examples
Result Information
Group: Programming |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax:
PRE_DIRECTIVE_MACRO_ARG |
Impact: Low |
Version History
Introduced in R2018a
See Also
MISRA C:2012 Rule 20.6
| Find defects (-checkers)
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)