Q90 What is bit field in C?

Bit fields in C

In order to save the memory bits are packed in integer is called bit fields.

In C, we can specify size (in bits) of structure and union members. The idea is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range.

struct {

int gender;

int win;

} match;

The above structure requires 8 bytes of memory space but in actual we are going to store either male(1) or female(0) and for second variable (win) yes(1) or no(0) and these can be noted as 1 or 0 respectively  in each of the variables. So to store values of above structure members 1 bit is enough. The C programming language offers a better way to utilize the memory space in such situation. If you are using such variables inside a structure then you can define the width of a variable which tells the C compiler that you are going to use only those number of bytes.

See an example how  above structure can be re-written as follows using bit fields:

struct {

int gender : 1;

int win : 1;

} match;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.