34
Bit Fields in C Language

Suppose a C program contains a number of TRUE/FALSE variables in a structure as follows:

struct abc
{
  unsigned int a;
  unsigned int b;
};

This structure requires 8 bytes of memory space but in actual we are going to store either 0 or 1 in each of the variables. If we use such variables inside a structure then we can define the width of a variable which specifies that we are going to use only those number of bytes. For example, above structure can be modified as follows:

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

Now, the above structure will require 4 bytes of memory space for status variable but only 2 bits will be used to store the values. If you will use up to 32 variables each one with a width of 1 bit , then also status structure will use 4 bytes, but as soon as you will have 33 variables, then it will allocate next slot of the memory and it will start using 8 bytes.
For example:

struct abc1
{
  int a;
  int b;
} ;

struct abc2
{
  int a : 1;
  int b : 1;
} ;

int main( )
{
   printf( "Memory size occupied by abc1 : %zu\n", sizeof(struct abc1));
   printf( "Memory size occupied by abc2 : %zu\n", sizeof(struct abc2));
   return 0;
}

Output :

Memory size occupied by abc1 : 8
Memory size occupied by abc2 : 4

Author

?