Reputation: 505
I have a union with a great number of fields, some of indeterminate size. I'd like to create a preset value (in the vein of NULL) where every field of the union is zero. I tried the following, but without optimization it would probably result in two copies; and more importantly doesn't actually work.
Header:
extern union MyUnion my_union_zero;
Source:
static char my_union_zero_arr[sizeof(union MyUnion)] = {0};
union MyUnion my_union_zero = (union MyUnion)my_union_zero_arr;
Am I missing something obvious? Is there a standard way to accomplish this?
Upvotes: 1
Views: 338
Reputation: 45654
Just use
static union MyUnion my_union_zero;
and rely on the compiler to do all the zero-initialization.
After this point only legalese and history. Read on if you like.
From n1331 paraphrazed:
K&R-C: Uninitialized static objects start out as 0. (Take note there is no reference to null-pointers being weird.)
Static and external variables which are not initialized are guaranteed to start off as 0; automatic and register variables which are not initialized are guaranteed to start off as garbage.
C89: All arithmetic members are initialized to 0 and all pointer-members to null-pointer. (Take note that padding was forgotten (and in this case is non-existant for union
s anyway. Also, noone took note that null-pointers might not be all-bits-zero yet.)
If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
DR_016: Reminds of null-pointer being weird, which would make many union
s ill-formed. Committee-decision that only the first member was to be initialized, which breaks many programs (though was not intended to).
C99: Incorporated that DR-resolution, to get:
- if it is a union, the first named member is initialized (recursively) according to these rules.
C11: Corrected that error:
6.7.9 Initialization
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
- if it has pointer type, it is initialized to a null pointer;
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
- if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
- if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
Upvotes: 7
Reputation: 53006
Compiler time version would be
static union MyUnion my_union_zero = {
.field1 = 0,
.
.
.
.fieldN = 0
};
Upvotes: 1