Working with typedef enums in structs and avoiding

2019-06-27 09:35发布

问题:

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

I have a typedef enum with a few items in it and I added an element to a struct of that new type

typedef enum
{
    foo1,
    foo2
} foo_t;

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

Now I want to create an instance of bar_t and initialize all of its memory to 0.

bar_t bar = { 0u };

This generates a warning that I mixing an enumerated with another type. The IAR specific warning number is Pe188. It compiles and works just fine since an enum is an unsigned int at the end of the day. But I'd like to avoid a thousand naggy warnings. What's a clean way to initialize struct types that have enumerated types in them to 0?

for the sake of argument lets assume bar_t has a lot of members - I want to just set them all to 0. I'd rather not type out something like this:

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

EDIT: Extra note: I am complying with MISRA. So if a workaround is going to violate MISRA it just moves the problem for me. I'll get nagged by the MISRA checker instead.

回答1:

If you really, literally want to initialize all the memory of a struct to 0, then that's spelled

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

That's actually fairly common, and it even tends to work, but technically it's incorrect for what most people actually want. It is not guaranteed to do the right thing for most element types, because C makes fewer guarantees than many people think about the representations of values of different types, and about the meaning of various bit patterns.

The correct way to initialize an aggregate object (such as a struct) as if assigning the value zero to every element is what you started with, though the canonical way to write it is simply

bar_t bar = { 0 };

(no need for the 'u' suffix). There is a remote possibility that that variant would avoid the compiler warning, though I wouldn't really expect so.

Ashalynd gives the answer I think is most correct (that is,

bar_t bar = { foo1 };

). If that somehow violates code conventions with which you must comply, then perhaps you could reorganize your struct so that the first element is of any type other than an enum type.