首先,这类似于:如何隐式转换整数类型?但是有一个不同的MISRA警告.
编译器不会生成MISRA错误,但静态分析工具会生成错误.我有一张正在进行工具制造商的票.
鉴于:
#include <stdio.h>
enum Color {RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE};
int main(void)
{
enum Color my_color;
my_color = BLUE;
if (my_color == YELLOW) // Generates MISRA violation, see below.
{
printf("Color is yellow.\n");
}
else
{
printf("Color is not yellow.\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
静态分析工具正在为if语句生成MISRA违规:
MISRA-2004 Rule 10.1 violation: implicitly changing the signedness of an expression.
Converting "4", with underlying type "char" (8 bits, signed),
to type "unsigned int" (32 bits, unsigned) with different signedness.
Run Code Online (Sandbox Code Playgroud)
编译器是正确的(不识别缺陷)还是静态分析工具?
根据C语言规范,表达式的类型:
typedef enum Colors {RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE} Colors_t;
Run Code Online (Sandbox Code Playgroud)
是一个signed int.
同样根据语言,枚举项的值是可以包含整个枚举的最小单位.所以在上面的枚举中,BLUE有类型signed char.
当变量与以下项Colors_t比较时,静态分析工具报告MISRA违规BLUE:
Colors_t my_color;
if (my_color == BLUE) // This generates a MISRA violation.
Run Code Online (Sandbox Code Playgroud)
将违规行为与之进行signed int比较signed char.
此外,枚举项可以与其他枚举类型混合而不会出错,因为枚举不是唯一类型:
typedef enum Tree_Species {REDWOOD, CYPRUS, PALM, OAK, JUNIPER, SEGUARO} Tree_Species_t;
Tree_Species_t my_tree;
my_tree = BLUE;
Run Code Online (Sandbox Code Playgroud)