Main Content

MISRA C:2023 Dir 4.9

A function should be used in preference to a function-like macro where they are interchangeable

Since R2024a

Description

Directive Definition

A function should be used in preference to a function-like macro where they are interchangeable.

Rationale

When feasible, use functions instead of macros. Functions perform argument type-checking and evaluate their arguments once, avoiding problems with potential multiple side effects.

Polyspace Implementation

Polyspace® reports violations of this rule for all function-like macro definitions.

As an exception, Polyspace does not report a violation of this rule if you use function like macros for _Generic selection.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the function-like macro MAX evaluates its arguments multiple times. After invoking this macro, the value of x and y are six and 12, respectively, which is unexpected. Polyspace reports a violation on the function like macro

#include <stdio.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))  //Noncompliant

int main() {
	int x = 5;
	int y = 10;
	int max = MAX(x++, y++);

	printf("max: %d\n", max);
	printf("x: %d\n", x);
	printf("y: %d\n", y);
	return 0;
}

Check Information

Group: Code design
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a