Main Content

MISRA C++:2008 Rule 16-0-6

In the definition of a function-like macro, each instance of a parameter shall be enclosed in parentheses, unless it is used as the operand of # or ##

Description

Rule Definition

In the definition of a function-like macro, each instance of a parameter shall be enclosed in parentheses, unless it is used as the operand of # or ##.

Rationale

When you invoke function-like macros, the compiler expands the macro by replacing its parameters with the tokens. Then the compiler substitutes the expanded macro into the code. This expansion and substitution process does not take precedence of operation into account. The function-like macros might produce unexpected results if their parameters are not enclosed in parenthesis. For instance, consider this function-like macro:

#define dustance_from_ten(x) x>10? x-10:10-x
The macro is intended to measure the distance of a number from ten. When you invoke the macro with the argument (a-b), the macro expands to:
a-b>10: a-b-10:10-a-b
The expression 10-a-b is equivalent to 10-(a+b) instead of the intended distance 10-(a-b). This unexpected behavior might result in errors and bugs. To avoid such unexpected behaviors, enclose parameters of a function-like macro in parentheses.

The exception to this rule is when a parameter is used as an operand of # or ##.

Polyspace Implementation

Polyspace® flags function-like macro definitions if the parameters are not enclosed in parenthesis. Polyspace does not flag unparenthesized parameters if they are preceded by the operators ., ->, or the characters #, ##.

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<iostream>
#include<cmath>
#define abs(x) (x>0) ? x:-x //Noncompliant

double foo(double num1, double num2){
	return log(abs(num1-num2));
}

int main(){
	std::cout<<foo(10,10.5);
}

In this example, when you invoke foo(10,10.5), you might expect the output to be log(0.5) or -0.69. Because the parameters of abs are not enclosed in parentheses, the output becomes log(-20.5) or NaN, which is unexpected and might lead to bugs. Polyspace flags the function-like macro definition.

Check Information

Group: Preprocessing Directives
Category: Required

Version History

Introduced in R2013b