Is zero initialization of structures guaranteed to wipe padded areas?

前端 未结 3 1732
太阳男子
太阳男子 2020-12-19 00:12

Suppose I have the following structure:

typedef struct
{
    unsigned field1 :1;
    unsigned field2 :1;
    unsigned field3 :1;
} mytype;

3条回答
  •  攒了一身酷
    2020-12-19 01:04

    The C99 standard doesn't specify the padding bits would be set to zero. In fact, it specifically mentions that the values of any padding bits are unspecified, so that padding need not be copied in an assignment.

    Footnote 51 to 6.2.6.1 (6) (n1570):

    Thus, for example, structure assignment need not copy any padding bits.

    The new C2011 standard - thanks to Jens Gustedt for sharing that knowledge - specifies that padding bits in objects of static or thread storage duration without explicit initialisation are initialised to 0.

    There are still no guarantees for assignment.

提交回复
热议问题