is it bad practice to have bit-fields and other data types as fields in a single struct in C90?

246 views Asked by At

I have this struct in C:

typedef struct Set {
    unsigned int state : 1;
    char array[LEN];
} Set;

While this compiles and executes I noticed that the bit-field actually alters one bit in the char array itself! So it I'm wondering if this is some known issue and it is bad practice to have bit-fields with other data types in one struct or I'm not doing something correctly.

1

There are 1 answers

0
Bathsheba On BEST ANSWER

Hogwash!

Rest assured that elements of a struct are always laid out so they are disjoint in memory.

You program clearly has a construct that is causing undefined behaviour - most likely you are indexing array[-1] or similar.

(Unless some smart alec has written #define struct union: the behaviour of that is also undefined since you shouldn't redefine a keyword in C.)