主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Dir 4.9

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

自 R2024a 起

描述

指令定义

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

理由

如果可行,请使用函数而不是宏。函数会执行参量类型检查并评估其参量一次,从而避免可能产生多重副作用的问题。

Polyspace 实现

Polyspace® 会报告所有类似函数的宏定义违反此规则的情形。

作为例外,如果您使用类似函数的宏进行 _Generic 选择,则 Polyspace 不会报告违反此规则的情形。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

在此示例中,类似函数的宏 MAX 多次计算其参量。调用此宏后,xy 的值分别为 6 和 12,这是意外结果。Polyspace 会针对类似函数的宏报告违规情形

#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;
}

检查信息

组:代码设计
类别:建议
AGC 类别:建议

版本历史记录

在 R2024a 中推出