Regarding Bit Fields in Structure and Union

Viewed 82

When using bit fields inside structures like:

struct abc{
  int a:3;
  unsigned int b:1;
} t;

So, my question is, do variables (with set bit-fields) share the same memory space even inside structures? Because when I saw their representation it looked like - first, a will have 3 bits(from LSB) then 1 bit for b (MSB) and all in one 4-byte(32 bits) memory space.

In case of Unions:

typedef union abc {
  unsigned int a:32;
  int f:1;
} t;

int main()
{   t q;
    q.a = (unsigned int)(pow(2,32)-1);
    q.f = 1;
    cout << sizeof(t) << endl;
    cout << q.a << " " << q.f << endl;

    return 0;
}

First of all, the sizeof() operator returns 4 bytes as the maximum size for this union and as 32 bits are set for variable 1 then how can it even manage space for variable b?

Thank you for reading till the end, I'll really appreciate your answers.

0 Answers
Related