Search code examples
cenumsmisra

MISRA Violation Rule 10.1 and Enums


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?


Solution

  • Per the C language specification, the type of the expression:

    typedef enum Colors {RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE} Colors_t;  
    

    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, BLUE has the type signed char.

    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.
    

    The violation is signed int compared to signed char.

    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;