Main Content

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
  );
The checker flags similar usage in 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))
When you call 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

expand all

#include <stdio.h>

#define print(A) printf(#A)

void func(void) {
    print(
#ifdef SW
          "Message 1"
#else
          "Message 2"
#endif
         );
}

In this example, the preprocessor directives #ifdef and #endif occur in the argument to the function-like macro print().

Correction — Use Directives Outside Macro

One possible correction is to use the function-like macro multiple times in the branches of the #ifdef directive.

#include <stdio.h>

#define print(A) printf(#A)

void func(void) {
#ifdef SW
        print("Message 1");
#else  
        print("Message 2");
#endif 
}

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