Search code examples
cstructinitializationbit-fieldsansi-c

Initializing bit-fields


When you write

struct {
    unsigned a:3, b:2;
} x = {10, 11};

is x.b guaranteed to be 3 by ANSI C (C89)? I have read and reread the standard, but can't seem to find exactly that case.

For example, "result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type." speaks about computation, not about initialization. And moreover, bit-field is not really a type.

Also, (when speaking about unsigned t:4) "contains values in the range [0,15]", but it doesn't necessarily mean that initializer must be reduced modulo 16 to be mapped to [0,15].

Struct initialization is really painstakingly detailedly described, but I really can't seem to find exactly that behavior. (Of course compilers do exactly that. And IBM documentation says " when you assign a value that is out of range to a bit field, the low-order bit pattern is preserved and the appropriate bits are assigned.", but I'd like to know if ANSI C standardizes that.


Solution

  • WRT "speaks about computation, not about initialization", the C89 standard explicitly applies the rules of assignment and conversion to initialization. It also says:

    A bit-field is interpreted as an integral type consisting of the specified number of bits.

    Given those, while a compiler warning would clearly be in order, it seems that throwing away upper-order bits is guaranteed by the standard.