Bit-Sized structure field

I have 2 questions:

This code:

   struct employee
   {
      char name[20];
      int married :1;
   };

How many does married take in memory?

And if I have multiple bit-sized fields Does it good to put them in the same variable of keep them individual?

like:

struct employee
{
 char name[31];
 int married :1;
 int manager :2;
 int children :4;
};

Or

struct employee
{
 char name[31];
 int flage; /* one bit for married, one for manager, and 4 bits for children */
};

Which one is better in memory usage and why???

Answers


When you use int flage for storing information regarding married manager and children, it MAY take 2 bytes of memory for one object, and every time you have to access a particular information you have to perform bitwise operations on the flage variable. This will thus require some processing.

By using a bitfield, like int married:1; (you better use unsigned int), that means it MAY take just 1 byte of memory, therefore you MAY save memory (supposing your struct is not padded). As a bonus, you can access its bits directly.

So it should be better approach regarding memory and processing.


How many does married take in memory?

int : 1 takes one bit of memory in a storage unit of sizeof(int). Note, that because int is signed and the bitfield has only one bit, such a bitfield can take only two values: -1 and 0.


It depends on the compiler, and probably also the options you give to the compiler when building.

Packing the fields tightly might decrease access performance while gaining storage efficiency, which is why it can change if you e.g. tell the compiler to optimize for speed.

The bitfields can never occupy less than CHAR_BITS bits in memory, since otherwise each struct instance's starting address wouldn't fall on an exact char address, which it must do.

So the first example:

struct employee
{
    char name[20];
    int married :1;
};

will probably mean sizeof (struct employee) occupies 24 bytes, assuming sizeof (int) is 4 on your system. This would mean that if you added more bitfield members after married, the size wouldn't change until you had added 31 bits of fields.


Need Your Help