2

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?

PS7
  • 21
  • 1

2 Answers2

3

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

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
  • 1
    ok, so you're saying I use "u32 var : 8" and typecast it to enum each time I want to reference its members? Is that the only way? – PS7 Jan 19 '15 at 14:37
1

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.

gsg
  • 9,167
  • 1
  • 21
  • 23