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

Restrictions on bit-field types

Restrictions on bit-field types

What you'll learn: Why you can't treat bit-fields exactly like normal variables when it comes to memory addresses and pointers.

Bit-fields are a fantastic way to squeeze data into the smallest possible space, but because they don't play by the standard rules of memory, they come with a few strict limitations. In C, the smallest addressable unit of memory is a byte (usually 8 bits). Bit-fields, however, can be smaller than a byte, which creates a unique problem.

The address-of operator (&)

The most important restriction to remember is this: You cannot take the address of a bit-field.

Think of a standard variable like a house on a street. Every house has a unique mailing address. A bit-field, however, is like a specific shelf inside a cupboard within that house. While the house has a street address, the individual shelf does not.

In C code, this means you cannot use the & operator on a bit-field member. Because a bit-field might start in the middle of a byte, there is no way for a standard pointer to "point" to it, as pointers are designed to point to the start of a byte.

struct Controller {
    unsigned int status : 1;
    unsigned int mode   : 3;
};

struct Controller myCtrl;
// This will cause a compiler error:
// unsigned int *ptr = &myCtrl.status; 

Array and sizing limits

Because you cannot take the address of a bit-field, you also cannot create an array of bit-fields. Arrays rely on a concept called "pointer arithmetic"—the ability to jump from one address to the next by a fixed size. Since bit-fields don't have individual addresses, the math for an array simply wouldn't work.

Additionally, you cannot use the sizeof() operator directly on a bit-field. The sizeof() operator returns a value in bytes. Since a bit-field might be only 3 bits long, it doesn't represent a whole number of bytes, making the operator invalid for that specific member.

Type limitations

Finally, bit-fields are generally restricted to int, signed int, or unsigned int. While C99 added support for _Bool, you cannot use types like float, double, or long double for bit-fields. These types have complex internal structures that cannot be packed into a custom number of bits.

Key takeaway

You cannot use the address-of operator (&), create arrays, or use sizeof() on bit-fields because they do not start on unique byte boundaries.