Do unnamed bit fields have well-defined semantics?

Is the following code guaranteed for a normal and successful completion?

#include <assert.h> struct foo_s { union { struct { unsigned a : 10; unsigned : 6; }; struct { unsigned : 10; unsigned b : 6; }; struct { unsigned : 10; unsigned c : 6; }; }; }; int main () { struct foo_s f; fa = 0; fb = 1; assert(fa == 0); return 0; } 

In response to another question , the possibility was expressed that the assignment of a named bit field in a structure that also contains an unnamed bit field can lead to arbitrary data for writing to these bits. C.11 & sect; 6.7.2.1? 12 states:

Declaring a bit field without a declarator, but only a colon and a width, indicates an unnamed bit field.

My reading of this is that an unnamed bit field is just an ordinary bit field, with the only difference being that the value in these bits cannot be obtained directly by name. Is it possible to extrapolate using as-if logic and assign arbitrary data in these bits?

+8
c language-lawyer c11
source share
1 answer

Yes, I think that an implementation can write arbitrary bits into an unnamed bit field. I think that footnote 126 simply indicates why unnamed bit fields with a width greater than 0 were introduced:

An unauthorized element of the structure of a bit field is useful for filling in with external circuits.

Thus, basically unnamed bit fields have the same semantics, for example, pad bits. You simply cannot rely on their contents.

Allowing the implementation to basically ignore the unnamed bit field when writing to the adjacent named bit field a greatly facilitates the processing of this field a . The current value of the unnamed field does not need to be read, and recording can be performed atomically at a time. As with the padding bits, which may be contained in the structure.

+5
source share

All Articles