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

Unnamed bit-fields for padding

Unnamed bit-fields for padding

What you'll learn: How to use empty bit-field names to precisely align data and skip over unused gaps in memory.

The gap in the map

In previous lessons, we saw how bit-fields allow you to pack data into tiny spaces, like using 3 bits for a day of the week. However, hardware isn't always neat. Sometimes you are working with a hardware manual that says: "The first 2 bits are for Status, then there is a 4-bit gap that is reserved or ignored, and the last 2 bits are for Mode."

If you don't need to access those middle 4 bits, you shouldn't have to give them a name. This is where unnamed bit-fields come in. They act like "reserved seating" in your memory layout—they occupy space so that the subsequent fields land exactly where they belong, but they remain anonymous and unreachable in your code.

How to create a gap

To create a gap, you simply define a bit-field type and a width, but omit the variable name.

Think of it like a parking lot where some spots are blocked off with traffic cones. The spots still exist and take up physical room, but nobody can park a "variable" there.

#include <stdio.h>

struct Controller {
    unsigned int status : 2;   // Bits 0-1: Active data
    unsigned int        : 4;   // Unnamed: Skips bits 2-5 (Padding)
    unsigned int mode   : 2;   // Bits 6-7: Active data
};

int main() {
    struct Controller c;
    c.status = 3;
    c.mode = 1;

    // c.status and c.mode are accessible.
    // There is no way to read or write the 4 bits between them!
    
    printf("Size of struct: %lu byte\n", sizeof(c));
    return 0;
}

Why use them?

Unnamed bit-fields are essential for memory mapping. When your C program interacts directly with hardware registers, the bits must line up perfectly with the physical wires. If the hardware designer left a hole in the register design, your struct must mirror that hole.

By using unnamed bit-fields, you ensure that mode starts at exactly the 6th bit without cluttering your code with "dummy" variables like int reserved1; or int ignoreMe;. It makes your code cleaner and signals to other programmers that those specific bits are intentionally bypassed.

Key takeaway

Unnamed bit-fields act as anonymous spacers to ensure your data structures perfectly align with specific hardware or protocol memory layouts.