c - cannot take address of bit-field

sleepy_dog picture sleepy_dog · Nov 25, 2012 · Viewed 21.5k times · Source

Why cannot take address of bit-field?

How do I make a pointer to bit-field?

Here is the code...

struct bitfield {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 1;
    unsigned int d: 1;
};

int main(void)
{
    struct bitfield pipe = {
        .a = 1, .b = 0,
        .c = 0, .d = 0
    };
    printf("%d %d %d %d\n", pipe.a,
            pipe.b, pipe.c, pipe.d);
    printf("%p\n", &pipe.a); /* OPPS HERE */
    // error: cannot take address of bit-field ...
    return 0;
}

Answer

Matteo Italia picture Matteo Italia · Nov 25, 2012

Bitfields members are (typically) smaller than the granularity allowed by pointers, which is the granularity of chars (by definition of char, which by the way is mandated to be 8 bit long at least). So, a regular pointer doesn't cut it.

Also, it wouldn't be clear what would be the type of a pointer to a bitfield member, since to store/retrieve such a member the compiler must know exactly where it is located in the bitfield (and no "regular" pointer type can carry such information).

Finally, it's hardly a requested feature (bitfields aren't seen often in first place); bitfields are used to store information compactly or to build a packed representation of flags (e.g. to write to hardware ports), it's rare that you need a pointer to a single field of them - and if it's needed, you can always resort to a regular struct and convert to bitfield at the last moment.

For all these reasons, the standard says that bitfields members aren't addressable, period. It could be possible to overcome these obstacles (e.g. by defining special pointer types that store all the information needed to access a bitfield member), but it would be yet another overcomplicated dark corner of the language that nobody uses.