Suppose I have the following structure:
typedef struct
{
unsigned field1 :1;
unsigned field2 :1;
unsigned field3 :1;
} mytype;
The first 3 bits will be usable but sizeof(mytype) will return 4 which means 29 bits of padding.
My question is, are these padding bits guaranteed by the standard to be zero initialized by the statement:
mytype testfields = {0};
or:
mytype myfields = {1, 1, 1};
Such that it’s safe to perform the following memcmp() on the assumption that bits 4..29 will be zero and therefore won’t affect the comparison:
if ( memcmp(&myfields, &testfields, sizeof(myfields)) == 0 )
printf("Fields have no bits set\n");
else
printf("Fields have bits set\n");
Yes and no. The actual standard, C11, specifies:
So this only holds for objects of static storage, at a first view. But then later it says in addition:
So this means that padding inside sub-structures that are not initialized explicitly is zero-bit initialized.
In summarry, some padding in a structure is guaranteed to be zero-bit initialized, some isn’t. I don’t think that such a confusion is intentional, I will file a defect report for this.
Older versions didn’t have that at all. So with most existing compilers you’d have to be even more careful, since they don’t implement C11, yet. But AFAIR, clang already does on that behalf.
Also be aware that this only holds for initialization. Padding isn’t necessarily copied on assignment.