PS7
PS7

Reputation: 21

unions as bit fields inside structures

I have the following:

typedef enum {
green = 0;
orange = 1;
red = 2;
} color;

typedef enum {
proceed = 0;
prepare = 1;
stop = 2;
} state;

typedef union {
color a;
state b;
uint8_t reserved;
} status;

typedef struct {

u32 m : 8;
u32 n : 8;
status var : 8;
u32 res : 8;

} info;

I am seeing a compilation error when I define a structure variable:

error: bit-field 'var' has invalid type.

I would like to pack the structure within the 4 bytes, and make the union of enums as a bit field. Is this possible?

Upvotes: 2

Views: 1008

Answers (2)

gsg
gsg

Reputation: 9377

If you already know the layout you want, best to ask for it as directly as possible. Probably something like:

typedef struct {
    uint8_t m;
    uint8_t n;
    uint8_t var;
    uint8_t res;
} info;

Use an explicitly sized type if you want a particular size. An enum type or union containing a member of enum type is allowed to be (at least) the same size as int, so your desire for this specific layout rules that out.

Upvotes: 1

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

Bit fields are defined and restricted only to data types int, signed int, unsigned int but nit for union type as per C89 or C90 standard. Bit Field, applies both for C/C++, with _Bool type defined in C99

Upvotes: 3

Related Questions