False "Implicit casts should not lower precision" code smells on enumerations in embedded C project with "-fshort-enums"

Hello,

We have embedded C project using GNU ARM Embedded toolchain, which defaults to using “-fshort-enums” setting for enumerations.

GCC documentation for this option says: “Allocate to an enum type only as many bytes as it needs for the declared range of possible values. Specifically, the enum type is equivalent to the smallest integer type that has enough room.”
ARM compiler documentation is more expressive: Documentation – Arm Developer

With Sonar way C rules, we get a lot of “Implicit casts should not lower precision” code smells when passing ‘short’ enumeration variables to, for example, uint8_t type variables.

For example,

#include <stdint.h>

// short_enum_t has unsigned 8-bit integer type (with GCC -fshort-enum)
typedef enum {
  enum_value_0 = 0,
  enum_value_1
} short_enum_t;

int func(uint8_t p)
{
  return p;
}

int main(void)
{
  short_enum_t val = enum_value_1;
  return func(val); // <-- code smell, implicit conversion loses integer precision: 'short_enum_t' to 'uint8_t' (aka 'unsigned char')
}

That code smell looks wrong in this context, enumeration has 8-bit integer type and value is passed to 8-bit integer type. Is there way to make Sonar know about “-fshort-enums” setting? Is there way to disable “Implicit casts should not lower precision” rule specifically for implicit enumeration conversions? I would not want to disable this rule completely as implicit “integer->integer”, “floating->floating” and “floating->integer” cast code smells are still useful.

-Jussi

Hi @jkivilin ,

thank you for the report, I managed to reproduce it and created a ticket to handle it: CPP-3288.