What is zero-width bit field

manav m-n picture manav m-n · Dec 10, 2012 · Viewed 10.4k times · Source

Possible Duplicate:
Practical Use of Zero-Length Bitfields

Why some structures have zero-width bit fields, and why is it required?

struct foo {
  int    a:3;
  int    b:2;
  int     :0; // Force alignment to next boundary.
  int    c:4;
  int    d:3;
};

int main()
{
        int i = 0xFFFF;
        struct foo *f = (struct foo *)&i;
        printf("a=%d\nb=%d\nc=%d\nd=%d\n", f->a, f->b, f->c, f->d);
        return 0;
}

The output of above program is

manav@os-team:~/programs/test$ ./a.out
a=-1
b=-1
c=-8
d=0

Please explain why these values are negative, and the memory layout of these variables inside the structure?

Answer

Paul R picture Paul R · Dec 10, 2012

From this first hit on a Google search:

Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A zero-width bit field can cause the next field to be aligned on the next container boundary where the container is the same size as the underlying type of the bit field.

As for the second part of your question, you set some of the bitfields in your struct to all 1s, and since these fields are signed then this results in a negative value for these fields. You can see this more effectively if you set the entire struct to 1s and look at the values in both signed and unsigned representations, e.g.

int main()
{
    struct foo f;
    memset(&f, 0xff, sizeof(f));
    printf("a=%d\nb=%d\nc=%d\nd=%d\n", f.a, f.b, f.c, f.d); // print fields as signed
    printf("a=%u\nb=%u\nc=%u\nd=%u\n", f.a, f.b, f.c, f.d); // print fields as unsigned
    return 0;
}