Working with typedef enums in structs and avoiding type confusion warnings

I am working with C99. My compiler is IAR Embedded workbench, but I assume this question will be valid for some other compilers as well.

I have an enum typedef with multiple elements in it and I added an element to the structure of this new type

typedef enum
{
    foo1,
    foo2
} foo_t;

typedef struct
{
    foo_t my_foo;
    ...
} bar_t;

      

Now I want to instantiate bar_t and initialize all of its memory to 0.

bar_t bar = { 0u };

      

This generates a warning that I am mixing an enum with a different type. The specific IAR warning number is Pe188. It compiles and works fine as the enum is an unsigned int at the end of the day. But I would like to avoid a thousand annoying warnings. What's a clean way to initialize the types of structs that enumerated the types in them to 0?

for the argument lets us assume that bar_t has many members - I just want to set them all to 0. I'd rather not type something like this:

bar_t bar = { foo1, 0u, some_symbol,... , 0u};

      

EDIT: Additional note: I am MISRA compliant. So if the workaround breaks MISRA, it will just move the issue for me. Instead, it will ask me for the MISRA checker.

+3


source to share


1 answer


If you really want to literally initialize all memory of the structure to 0, then this is written

memset(&bar, 0, sizeof(bar_t));

      

This is actually quite common and it even tends to work, but technically it is not true for most people who really want to. This is not guaranteed to be correct for most element types, because C provides fewer guarantees than many people think about the representations of values โ€‹โ€‹of different types and the meaning of different bit patterns.

The correct way to initialize an aggregated object (like a struct), as if assigning a value of zero to each element, is where you started, although the canonical way of writing it is just

bar_t bar = { 0 };

      



(no need for the 'u' suffix). There is a remote possibility that this option will avoid a compiler warning, although I would not have expected it.

Ashalind gives the answer that I think is the most correct (i.e.

bar_t bar = { foo1 };

      

). If that somehow violates the coding conventions that you must conform to, perhaps you could refactor yours struct

so that the first element is of any type other than a type enum

.

+1


source







All Articles