Search code examples
cgcccompiler-warningsinteger-overflow

is this bit field of size one actually overflowing when assigning 1?


I have written some code with bit fields that I thought should work, but it seems like GCC disagrees. Did I miss something or did I actually find a bug in GCC?

After simplifying my code, the testcase is quite simple. I'm assigning the integer literal 1 to a bitfield that has a size of one bit:

typedef struct bitfield
{
    int bit : 1;
} bitfield;

bitfield test()
{
    bitfield field = {1};
    return field;
}

If I compile this with GCC 6.2.1 (same with 5.4.0), I get the following warning (with -pedantic):

gcc -fPIC test.c -pedantic -shared
test.c: In function ‘test’:
test.c:8:23: warning: overflow in implicit constant conversion [-Woverflow]
     bitfield field = {1};
                       ^

The strange thing is: When I replace -pedantic with -Woverflow, the warning disappears.

I don't get any warnings with clang.


Solution

  • Use unsigned int for this bit field. A 1-bit signed number can only hold 0 and -1.

    typedef struct bitfield
    {
        unsigned int bit : 1;
    } bitfield;