メインコンテンツ

MISRA C++:2023 Rule 19.3.5

Tokens that look like a preprocessing directive shall not occur within a macro argument

Since R2024b

Description

Rule Definition

Tokens that look like a preprocessing directive shall not occur within a macro argument. 1

Rationale

When a compiler encounters function-like macros, it replaces the argument of the macro into the replacement code. If an argument contains a token that looks like preprocessing directives, the replacement process during macro expansion is undefined. Depending on the environment, such a function-like macro can behave in unexpected ways, leading to errors and bugs.

Polyspace Implementation

Polyspace® reports a violation on a function-like macro if an argument of the macro contains the character #. Polyspace reports a violation only on the first preprocessing directive within the function-like macro.

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

#include<cstdlib>
#include<iostream>
#define PRINT(ARG) std::cout << #ARG
//....
#define Error1
//...


void foo(void){
	PRINT(
	#ifdef Error1  //Noncompliant  
	"Error 1"
	#else
	"Error 2"
	#endif 
	);
	
}

In this example, the function-like macro PRINT is invoked with an argument that chooses between two strings by using an #ifdef block. Depending on the environment, the code can output either of these values:

  • Error 1

  • #ifdef Error1 //Noncompliant "Error 1" #else "Error 2" #endif //Noncompliant

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2024b

expand all


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.