When the question of saving memory is at the priority, we can group variables requiring a few bits as a single word (i.e. single integer), instead of defining each variable as an integer or character. This can be done using bitfields
What are bitfields?
One-bit can give values (true/false). Value of 2-bits can range from 0 to 4. Value of 3-bits can range from 0 through 7. Several such data items can be combined into an individual word of memory. Such data items are called bit-fields are defined as members of structure.
Each member name is followed by a semicolon and an unsigned integer indicating field size. Variable definition and accessing each member is same as ordinary structure.
If we have to store the information of an employee like:
Thus we declare the structure as
The number after the colon specifies the size of each bit-field. It is defined as a structure, which is subdivided into 3 bit fields. They have width of 1, 2 and 3. Hence they occupy 6 bits within a word of memory.
Let us write a small program using the given bitfield structure
//program demonstrating use of bitfields
Gender =0 Marital Status =1 Department =0
Requires: 4 bytes
Values are assigned to bitfields using #defines. Bitfields can also be initialized. Bitfields can appear in arithmetic expressions.
Arrays of bitfields are not allowed. The (&) address operator cannot be applied to a bitfield, pointer cannot access a bitfield and a function cannot return a bitfield.
A bitfield without a name can be used for padding.
A bitfield can be forced to start at a beginning of a new word by specifying unnamed bitfield of width 0.
C Related Interview Questions
|DBMS Interview Questions||C++ Interview Questions|
|C & Data Structures Interview Questions||Java Interview Questions|
|Go (programming language) Interview Questions||F Sharp (programming language) Interview Questions|
|C preprocessor Interview Questions||R Programming language Interview Questions|
|D Programming Language Interview Questions||Lua (programming language) Interview Questions|
|Embedded C Interview Questions|
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.