Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operation with (signed) enum value

I am using enumerator values for flags:

typedef enum
{
    a = 0x00,
    b = 0x01u, // the u has no influence, as expected
    c = 0x02u, // the u has no influence, as expected
...
} enum_name;

volatile unsigned char* reg = SomeAddress;
*reg |= b;

According to MISRA-C:2004 bitwise operations shall not be done with a signed type. Unfortunately, My compiler IAR use signed int (or short or char) as underlying type of enums, and the only option I can find relates to the size, not the signedness ("--enum-is-int").

like image 540
lkanab Avatar asked Jun 10 '26 23:06

lkanab


1 Answers

According to the IAR C/C++ Development Guide for ARM, pages 169 and 211, you can define the type of your enums if you enable the IAR language extensions (-e command-line option, or Project > Options > C/C++ Compiler > Language > Allow IAR extensions in the IDE).

In particular, you should define an extra "sentinel" value, to make sure the compiler chooses the correct type. It prefers signed types, and uses smallest possible integer type, so the sentinel should be the largest positive integer the corresponding unsigned integer type can describe. For example,

typedef enum {
    /* ... */
    enum_u8_sentinel = 255U
} enum_u8;

typedef enum {
    /* ... */
    enum_u16_sentinel = 65535U
} enum_u16;

typedef enum {
    /* ... */
    enum_u32_sentinel = 4294967295UL
} enum_u32;
like image 70
Nominal Animal Avatar answered Jun 12 '26 12:06

Nominal Animal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!