MISRA违反规则10.1和枚举 [英] MISRA Violation Rule 10.1 and Enums
问题描述
首先,这类似于:如何隐式转换整数类型?,但带有不同的MISRA警告.
First off, this is similar to: How are integer types converted implicitly? but with a different MISRA warning.
编译器不会生成MISRA错误,但是静态分析工具会生成.我正在与工具制造商取得票证.
The compiler does not generate a MISRA error, but the static analysis tool does. I have a ticket with the tool manufacturer in progress.
给出:
#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;
}
静态分析工具正在为if
语句生成MISRA违规:
The static analysis tool is generating a MISRA violation for the if
statement:
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.
编译器是正确的(不能识别缺陷)还是静态分析工具?
Is the compiler correct (not identifying the defect) or the static analysis tool?
推荐答案
根据C语言规范,表达式的类型:
Per the C language specification, the type of the expression:
typedef enum Colors {RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE} Colors_t;
是signed int
.
也根据语言,枚举项的值是可以包含整个枚举的最小单位.因此,在上面的枚举中,BLUE
具有类型signed char
.
Also according the language, the value of an enumerated item is the smallest unit that can contain the entire enumeration. So in the above enumeration, BLUE
has the type signed char
.
将变量Colors_t
与BLUE
进行比较时,静态分析工具报告MISRA违规:
The static analysis tools are reporting a MISRA violation when a variable of Colors_t
is compared to BLUE
:
Colors_t my_color;
if (my_color == BLUE) // This generates a MISRA violation.
与signed char
相比,违规为signed int
.
此外,枚举项可以与其他枚举类型混合而不会出错,因为枚举不是唯一类型:
Also, the enumeration items can be mixed with other enumeration types without error, since the enumerations are not a unique type:
typedef enum Tree_Species {REDWOOD, CYPRUS, PALM, OAK, JUNIPER, SEGUARO} Tree_Species_t;
Tree_Species_t my_tree;
my_tree = BLUE;
这篇关于MISRA违反规则10.1和枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!