Reputation: 59
Recently i faced a problem with bit fields
union u
{
struct
{
unsigned char x : 2;
unsigned int y : 2;
}p;
int x;
};
int main()
{
union u u = { 2 };
printf("%d\n", u.p.x);
}
Its printing 2 actually as per the little endian rule. bitfield y should be assigned 2 why 2 is assigned to x
Upvotes: 2
Views: 44
Reputation: 3204
When using
union u u = { 2 };
you are actaully assigning the member u.p.x
as it is the first member of struct p
according to
When initializing a union, the initializer list must have only one member, which initializes the first member of the union unless a designated initializer is used (since C99). cppreference
if you want initialize u.p.y
use:
union u u = { {.y = 2} };
or
union u ux = { .p={ 0,2 } };
Upvotes: 1