Search code examples
cstructuresizeofbit-fields

Why does sizeof unnamed bitfield member structure print 1?


In the following program, declared unnamed bitfield member in structure.

#include <stdio.h>

struct st{
    int : 1;
};

int main()
{
    struct st s;
    printf("%zu\n",sizeof(s));  // print 1
}

Above program print the output 1.

Why does sizeof(s) print 1?


Solution

  • The sizeof(s) is undefined because there is no other named member in the structure.

    C11 6.7.2.1(P8) :

    The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit. The struct-declaration-list is a sequence of declarations for the members of the structure or union. If the struct-declaration-list contains no named members, no anonymous structures, and no anonymous unions, the behavior is undefined. The type is incomplete until immediately after the } that terminates the list, and complete thereafter.

    If you write like this:

    struct st{
            int : 1;
            int i : 5;
        };
    

    So,sizeof(s) is ok because there is also named bit-field member in structure.