Bit Fields in C

Bit field is a data structure that helps in allocating memory to structure and unions in bits. It helps in saving memory or is useful in optimizing the structure’s size or union’s size.

Please refer to the structure and structure padding in C for a better understanding of the below concepts:

Example:

Consider a structure with two fields which are boolean.

Without using Fields

#include <stdio.h>
struct flag
{
   unsigned int flag1;
   unsigned int flag2;
};
  
int main()
{
   struct flag obj;
   pritf("\n Size of structure is :%d\n",sizeof(struct flag));
   return 0;
}

Output:

Size of structure is: 8 

Now with bit fields

#include <stdio.h>
  struct flag
  {
     unsigned int flag1:1;
     unsigned int flag2:1;
  };
  
  int main()
  {
     struct flag obj;
     pritf("\n Size of structure is :%d\n",sizeof(struct flag));
     return 0;
   }

Output:

Size of structure is: 4

In the above program 4 bytes of space is saved.

There are some limitations with respect to these bit fields, however:

  • Cannot scanf () directly into bit fields.
  • Pointers cannot be used on bit fields to access them.
  • Cannot have an array of bit fields.


Categories: C Language

Leave a comment