Skip to study material
← Question index

QUESTION 16

Explain structure bit-fields, uses and limitations.

5 marks

Answer in brief

Bit-fields describe small-width integer members, often used for compact flags or bounded state values.

Declaration

struct Flags {
    unsigned int ready : 1;
    unsigned int mode : 2;
};

Meaning

ready can hold 0 or 1. mode can hold 0 through 3 for this unsigned two-bit field. Access uses the normal dot or arrow member operators. Assign only values suitable for the field’s width and intended meaning.

Uses

  1. Represent several yes/no flags in one record.
  2. Store small status values when the implementation’s layout is acceptable.
  3. Give meaningful field names rather than repeatedly writing manual bit masks.

Limitations

The packing order and allocation-unit details are implementation-dependent. Do not use a bit-field structure as a portable network packet or file format without an explicit external encoding. A bit-field is not an addressable ordinary object: its address cannot be taken with &. sizeof cannot be applied to a bit-field expression.

Type and layout rules

For introductory portable declarations, use unsigned int, signed int or _Bool as appropriate. Plain int field signedness is implementation-defined. A zero-width unnamed field has a layout purpose and is not a normal named value. Do not promise a particular total byte saving: padding and packing rules vary.

Example and complexity

The program assigns ready = 1 and mode = 3, then displays their promoted values. Each fixed field operation is O(1) in the usual model. Bit-fields improve a representation only when their restrictions fit the task.

Complete C example

main.c

Download main.c
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Flags { unsigned int ready : 1; unsigned int mode : 2; };

int main(void)
{
    struct Flags f = {0};
    f.ready = 1; f.mode = 3;
    printf("Ready = %u, mode = %u\n", (unsigned)f.ready, (unsigned)f.mode);
    return 0;
}

Sample input and output

The example uses values in the code.

Output

Ready = 1, mode = 3