Bit Field
There might be scenario when we know that that member of structure will take very short range of values and for storing that values we don’t need full memory allocated for that variable.
example:-
struct test
{
int male_allowed;
int female_allowed;
};
in the above structure we have two member male_allowed and female_allowed. Both are just a status variables whose value will be either 0 or 1. So for storing 0 or 1 we need only 1 bit. so we can say total 2 bit are needed for structure test. 1 bit for male_allowed and 1 bit for female_allowed. but the size of above structure is 8 byte or 64 bit in case of 32 bit OS. But we will be actually using only 2 bits out of total 64 bit.Rest 62 bits will not be used and hence memory will be wasted.
To overcome this problem C provide us a way to specify the number of bits required for each of member of a structure. This facility of specifying the actual memory use by members of structure is provided by bit field.
bit field declaration:
struct tag
{
type member_name:size;
};
tag:- tag is the name of structure which is optional.
type:- data type of the bit field.
member_name:- its the name of variable or bit field.
size:- number of bits required for member but this value should not be greater then the total size of data type of this member.
struct test{
unsigned int male_allowed:1;
unsigned int female_allowed:1;
};
in the above example by using of bit filed we specified that both the member of structure will use only 1 byte each. Total memory allocated for this structure will be 4 byte or 32 bits. So we saved 32 bit by using the bit field. These remaining 32 bit we can use for adding other member in structure.
Now you might be confused that when we need only 2 bits for the above structure and we have also specified the same then how come the size of structure is 32 bit.
Actually the size of structure will be multiple of 4 byte in case of 32 bit machine and 16 bit in case of 16 bit machine.
example:-
struct employee{
char name[20];
int empolyee_id:8;
}
As the above structures member consuming only 28 byte which is less then 32 bit hence the size of structure will be 32 in case of 32 bit machine. But if we are using more then 32 bit in structure then the size of structure will be next multiple of 32.
struct employee{
struct name[30];
int employee_id[8];
}
above structure need 38 bytes which is more than 32 bit hence next multiple of 32 means 64 bit will be allocated for this structure in case of 32 bit machine.