Course contentsShow
← C
Lesson 646 of 1,2199. Structures and UnionsFree lesson

Syntax for declaring bit-fields

Syntax for declaring bit-fields

What you'll learn: How to specify the exact number of bits a structure member should occupy to save memory.

Thinking in Bits

In standard C, the smallest data type you can usually work with is a char, which takes up 8 bits (1 byte). However, sometimes you need to store data that is much smaller. Imagine you are building a system to track a light switch (1 bit for On/Off) or the day of the week (3 bits to represent numbers 0–7). If you use a standard int for these, you are wasting 31 bits of space for every single variable.

Bit-fields allow you to pack these small pieces of data tightly together inside a struct. Think of a bit-field like a custom-sized storage container where you get to decide exactly how many "slots" (bits) it takes up on the shelf.

The Colon Syntax

To declare a bit-field, you define a struct as usual, but you add a colon (:) followed by a number after the member name. This number tells the compiler exactly how many bits to allocate.

struct DeviceStatus {
    unsigned int isOn : 1;      // Uses only 1 bit (0 or 1)
    unsigned int errorMode : 3; // Uses 3 bits (values 0 to 7)
    unsigned int colorCode : 4; // Uses 4 bits (values 0 to 15)
};

In the example above, the entire DeviceStatus struct technically fits into just 8 bits (1 byte). Without bit-fields, these three unsigned int variables would likely take up 12 bytes (96 bits) on a modern system.

Important Rules

When writing this syntax, keep these three rules in mind:

  1. Type Selection: Bit-fields are almost always declared as unsigned int or signed int. Using unsigned is the safest bet because you are usually dealing with raw binary patterns or small positive counts.
  2. The Limit: You cannot request more bits than the underlying type holds. If you are using an int that is 32 bits wide on your system, you cannot declare a bit-field of :33.
  3. No Addresses: Because bit-fields might not start at the beginning of a byte, you cannot use the address-of operator (&) on them. The computer can’t give you a memory address for "half of a byte."

By using the colon syntax, you gain granular control over your program's memory footprint, which is essential for low-level hardware programming or handling massive amounts of data efficiently.

Key takeaway

To declare a bit-field, follow a struct member's name with a colon and the specific number of bits it should occupy.