Misra warning C code - Comparison of boolean and unsigned values in if loop

Viewed 280

In the below C code, while checking the if condition, i am getting the Misra warning as

The operand of the opeartor '=='do not have same essential type category: one is 'Boolean' and other is 'unsigned'

In the header file file1.h

#define timer_4sec       (uint8)160
#define bool_rolltime    (roll_time_count < timer_4sec)

in the source file , file1.c

static uint8 roll_time_count = timer_4sec

void function()
{
  if(bool_rolltime == True)
  {
     printf("rolling ..\n");
  }
}
void function2()
{
    //update the roll_time_count status , increment and decrement static timer variable.
}

The problem is here if(bool_rolltime == True). I have understood that roll_time_count and timer_4sec are uint8 variables. So i have tried to fix this warning like this way

#define bool_rolltime    (bool)(roll_time_count < timer_4sec)

Is this code correct method to avoid the Misra error? If not please suggest how to avoid such warnings ?

1 Answers

This essentially the same question you asked yesterday. As I answered then, you need to tell your static analyser which types that are boolean. Such as bool, false and true. Why you are using some home-brewed standard True, I don't know, but it's not a good idea as you noticed. Similarly, drop home-brewed uint8 and use standard C uint8_t.

In addition, you get MISRA violations because of smelly macros hiding simple expressions. That's plain bad practice, MISRA or no MISRA. You shouldn't invent some mysterious macro language. Just keep it simple and readable:

#define timer_4sec       160u // no need for cast but you need the u suffix for MISRA-C

static uint8_t roll_time_count = timer_4sec;

void function (void) // empty parenthesis is obsolete C, write (void)
{
  if(roll_time_count < timer_4sec)
  {
     printf("rolling ..\n");
  }
}

Now that we kept the code simple and readable, it automatically turned MISRA-C compliant too. Both operands of < are of the same "unsigned" essential type category thanks to the 'u' suffix.

Again, like I already answered yesterday, you need to study the rules for essential type in the MISRA-C guidelines or you won't understand a thing of what the tool keeps telling you.

Related