First off, this is similar to: How are integer types converted implicitly? but with a different MISRA warning.
The compiler does not generate a MISRA error, but the static analysis tool does. I have a ticket with the tool manufacturer in progress.
Given:
#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;
}
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?
Per the C language specification, the type of the expression:
is a
signed int.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,
BLUEhas the typesigned char.The static analysis tools are reporting a MISRA violation when a variable of
Colors_tis compared toBLUE:The violation is
signed intcompared tosigned char.Also, the enumeration items can be mixed with other enumeration types without error, since the enumerations are not a unique type: