Reputation: 29096
I sometime use unions to access the same type of data differently. For example this union:
typedef union {
int64 word;
int32 array[2];
struct {
field4:16;
field3:16;
field2:28;
field1:4;
} bit;
} my_type;
Is this solution consensually correct and is there any standards for the names I used (word, array, bit)?
The bad point with this solution is the cumbersome notation I got:
my_type data;
data.bit.field1 = 0xA;
for(i=0;i<sizeof(my_t);i++)
data.array[i]++;
Upvotes: 1
Views: 1465
Reputation: 13690
Some compilers allow to omit the name of struct in a union. You can try to define your type as this:
typedef union {
int64 word;
int32 array[2];
struct {
field4:16;
field3:16;
field2:28;
field1:4;
} bit;
} my_type;
This allows to access the bit members a bit easier:
my_type data;
data.field1 = 0xA;
But unfortunately this is compiler and compiler options dependent. Edit: The C11 Standard draft describes this as anonymous struct.
Upvotes: 3