Zero-width bit-fields for alignment
What you'll learn: How to use a bit-field of size zero to force the next structure member to start at a new memory boundary.
The Problem: Tight Packing
Normally, bit-fields are the ultimate space-savers. If you define three 1-bit flags, the compiler bundles them into a single byte. While this is great for saving memory, there are times when you need a specific member to start fresh at the beginning of the next "unit" (the underlying storage type, like an unsigned int).
Think of bit-fields like people sitting on a bus. By default, the compiler tries to shove everyone into the same row to save space. If one person only takes up a sliver of a seat, the next person sits right next to them. But what if you need the next person to start in a brand new row for better organization or hardware requirements?
The Solution: The Zero-Width Gap
A zero-width bit-field is a special syntax—unsigned int : 0;—that tells the compiler: "Stop packing bits into the current unit. Even if there is room left, jump to the start of the next one."
It acts as a non-named separator. You cannot give it a name, and you cannot store data in it. Its only job is to provide alignment.
Code Example: Seeing the Jump
In the following example, we use a zero-width bit-field to ensure flag3 doesn't share a storage unit with the first two flags.
#include <stdio.h>
struct ControlPanel {
unsigned int flag1 : 1; // Uses 1 bit
unsigned int flag2 : 1; // Uses 1 bit, packed next to flag1
unsigned int : 0; // Force alignment to the next boundary
unsigned int flag3 : 1; // Starts in a new storage unit
};
int main() {
// On most systems, this will be 8 bytes instead of 4
// because the :0 forced flag3 into a new 'unsigned int' slot.
printf("Size of struct: %zu bytes\n", sizeof(struct ControlPanel));
return 0;
}
Why use this?
You will mostly use this when interfacing with hardware. If a device manual says "Bit 0 is the Power, Bit 1 is the Error, and then the Mode setting MUST start at the next 32-bit word," the zero-width bit-field is your best friend. It ensures your software structure perfectly mirrors the physical reality of the hardware registers without you having to manually calculate padding bits.
Key takeaway
A zero-width bit-field (: 0) acts as a manual break, forcing the compiler to start the next member at the beginning of the next memory storage unit.