Is this a compiler bug? Or just odd behaviour?

24 Aug 2010

I have a struct containing a single bitfield, and I get a warning "<bits.0> may be used before being set" when the struct is instantiated. (Actually I don't get that warning at all, I'll add another post about the incorrect warning in a second)

Here's the simplest repro step I've found:

 

struct Bitfield
{
    unsigned char bit1:1;
};

Bitfield Test()
{
    Bitfield bits; // "<bits.0> may be used before being set"
    
    bits.bit1 = 1;

    return bits;
}

It's not a huge deal, as it is only a warning, but I'm so used to always building with -wall it bugs me :)

 

It doesn't actually matter if I have a constructor or not, this example behaves identically:

 

struct Bitfield2
{
    Bitfield2()
    {
        bit1 = 0;
    }
    unsigned char bit1:1;
};

Bitfield2 Test2()
{
    Bitfield2 bits; // "<bits.0> may be used before being set"

    
    bits.bit1 = 1;
    
    return bits;
}
24 Aug 2010

Looks like it's been seen before. The ARM docs say, "The check is pessimistic and sometimes reports an anomaly where there is none". I was able to suppress it like this:

 

Bitfield2 Test2()
{
    Bitfield2 bits = {0};
    bits.bit1 = 1;    
    return bits;
}

By the way, why are you using bitfields? The code with them is generally longer and slower, and I doubt you're lacking memory. It's better to use native-sized (int) variables, unless you're dealing with file formats or such.

 

24 Aug 2010

Ahh, cool.

 

I nearly added a caveat to the original post because I knew there'd be some anti-bitfield comment. ;)

It's some old code that I was just porting across, I think that this warning's reason enough to re-write that section rather than just ignore it. :)

 

Normally I wouldn't use them at all, they're really evil.

The only marginally safe way to do bit manipulation is to use bitwise operations and shifts etc..., because the order that the bits appear in memory is completely compiler dependent. GCC even has flags to change the order, so you can end up linking objects from the same compiler that order the bits in one struct differently!

24 Aug 2010

Well, I wouldn't go as far as calling bitfields "evil", but indeed it's better not to use them unless you understand all the details. I think one area where they can be useful is structures for dealing with hardware registers.