Bools and bitfields

Patrick Horgan phorgan1@yahoo.com
Sun Dec 13 20:14:00 GMT 2009


Paulo J. Matos wrote:
> Hi,
>
> Regarding the size of possible bitfields I would like to know why:
> #include <stdbool.h>
> struct s {
>     bool f : 2;
> };
>
> fails to compile in gcc 4.3 and gcc 4.4 but not in gcc 4.2.
>
> sizeof(bool) is 1, and C99 6.7.2.1 paragraph 3 seems to imply that the
> bitfield size shouldn't be bigger than the width of the object.
>   
Using 4.4.1 is compiles fine as c++.  c++ standard says (excerpt from 
section 9.6 Bit-fields number 1):

      The value of the integral constant expression may be larger than 
the number of bits in the object representation (3.9) of the bit-field’s 
type; in such cases the extra bits are used as padding bits and do not 
participate in the value representation (3.9) of the bit-field.

So in C++ it's perfectly ok to have the width wider than the bit-field's 
type.

Compiling as C99 gets the following error:

error: width of ‘f’ exceeds its type

That's because the C99 spec says (under 6.7.2.1 Structure and union 
specifiers):

3 The expression that specifies the width of a bit-field shall be an 
integer constant
  expression with a nonnegative value that does not exceed the width of 
an object of the
  type that would be specified were the colon and expression omitted. If 
the value is zero,
  the declaration shall have no declarator.

since the width of a _Bool is 1 bit, (spec say: 2 An object declared as 
type _Bool is large enough to store the values 0 and 1) this is flagged 
as an error.

I have no idea why they chose this--I like the C++ idea of extra bits 
being used for padding.

Patrick







More information about the Gcc-help mailing list