主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 7.5

The argument of an integer constant macro shall have an appropriate form

自 R2024a 起

描述

规则定义

The argument of an integer constant macro shall have an appropriate form 1 .

此规则来自 MISRA C™:2012 Amendment 3。

理由

对整数常量宏使用不适当的参量形式可能会导致编译错误或代码行为未定义,原因包括意外替换、缺乏类型检查以及编译器的假设和优化混淆等。

Polyspace 实现

当使用整数常量宏的不适当形式的参量时,规则检查器会报告规则违反。整数常量宏的参量形式在以下情况下视为适当:

  • 参量是一个无后缀的整数字面量,例如十进制、八进制或十六进制。

  • 参量的值不超过宏名称所指示的等效精确宽度类型的限制。例如,UINT32_C 的参量必须可表示为无符号 32 位值。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <stdint.h>

int32_t example1 = INT32_C(42);            //Compliant
int32_t example2 = INT32_C(1.e1);          //Noncompliant
int32_t example3 = INT32_C( 0xDEADBEEF );  //Noncompliant
int32_t example4 = -INT32_C(5);            //Compliant
uint32_t example5 = UINT32_C(5UL);         //Noncompliant

在此代码中:

  • example1 是合规的,因为参量是一个无后缀的十进制整数,可以表示为有符号 32 位整数。

  • example2 不合规,因为 1.e1 是浮点数字面量,而非无后缀整数字面量。

  • example3 不合规,因为十六进制值 0xDEADBEEF 的整数值超出了 INT32_C 的限制。

  • example4 是合规的,因为减号运算符位于宏之外。

  • example5 不合规,因为 5UL 带有后缀。

检查信息

组:字面值和常量
类别:强制
AGC 类别:强制

版本历史记录

在 R2024a 中推出


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.