c - 整数类型是如何隐式转换的?

标签 c misra

以下代码在 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;
}
  • 为什么要转换逻辑表达式?
  • 这里转换了什么?
  • 当我交换 OneMyVariable 时,为什么代码通过了 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/

相关文章:

c - 嵌入式软件的 Misra 标准

c - 将值设置为数组(初始化后)

c 中的 char 具有多个字符但不是指针

c++ - MISRA 5-0-15 - 指针算术 - 违反规则

c - misra c 2004 "Implementation-defined behavior documented"规则 3.1 涵盖的问题

转换 NULL 指针函数参数导致违反 Misra 规则 11.3

java - 为什么大多数枚举值在声明中以 BUTT 说明符结尾?

c - 在 #if 中更改变量时出现问题

编译器能否将 `(void *) 0` 中的 `execl(prog, arg, (void*) 0)` 转换为适当类型的空指针?

C++ 内存管理和 Misra