Is the following code guaranteed to terminate normally and successfully?
#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;
f.a = 0;
f.b = 1;
assert(f.a == 0);
return 0;
}
While answering a different question, the possibility was raised that assignment to a named bit-field in a structure that also contains an unnamed bit-field may cause arbitrary data to be written to those bits. C.11 §6.7.2.1 ¶12 states:
A bit-field declaration with no 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 a regular bit-field, with the only difference being the value in those bits cannot be obtained directly by name. Is an implementation allowed to extrapolate from that using "as-if" logic and assign arbitrary data in those bits?
.a
and.b
are references to different (anonymous) members of the union.memset()
), are the bits still unpredictable?f.b = 1
may mess-upf.a
. OTH "There may be unnamed padding within a structure object, but not at its beginning." So it looks like your assertion "unnamed bit-field is just a regular bit-field" has creditability. (I've not used nor regularly seen unnamed bit fields so no experience. I give them dummy names.)