以下代码在 MISRA 检查中失败。具体报错信息为:
(MISRA-C:2004 10.1/R) The value of an expression of integer type shall not be implicitly converted to a different underlying type if it is not a conversion to a wider integer type of the same signedness
typedef enum _MyEnum { One, Two } MyEnum;
MyEnum MyVariable;
int foo(void)
{
int result = 1;
if (One == MyVariable) // fails here with MISRA-C:2004 10.1/R
{
result = 2;
}
return result;
}
- 为什么要转换逻辑表达式?
- 这里转换了什么?
- 当我交换
One
和MyVariable
时,为什么代码通过了 MISRA 检查?
编辑:编译器是 TI“MSP430 C/C++ 编译器 v4.0.0”,包含 MISRA 规则检查。
最佳答案
MISRA 检查器中没有错误,它的行为是正确的。您收到此错误是因为 C 标准存在缺陷且不合逻辑。
有两个项目:
One
是一个枚举常量。标准 §6.7.2.2/2 声明这应与int
兼容,没有异常(exception)。MyVariable
是一个枚举类型。标准 §6.7.7.2/4 指出这应该与 char、有符号整数类型或无符号整数类型兼容。适用的类型是实现定义的行为。
在您的例子中,实现定义的枚举类型似乎等于 unsigned int。
因此代码试图隐式地将 signed int 变量转换为 unsigned int,这违反了 MISRA 2004 10.1。
符合 MISRA 的代码应该是 if (One == (MyEnum)MyVariable)
。
关于c - 整数类型是如何隐式转换的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582523/