union-type initialization

From cppreference.com
< c‎ | language

Template:c/language/initialization/navbar

This is the initialization performed when a union is constructed.

[edit] Explanation

If a union has automatic storage duration and is not initialized explicitly, its initial value is indeterminate.

If a union has static or thread storage duration and is not initialized explicitly, then the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits. If the first member has

  • pointer type, it is initialized to a null pointer;
  • arithmetic type, it is initialized to (positive or unsigned) zero;
  • aggregate type, it is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • union type, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits.

The initializer for a union object that has automatic storage duration shall be either an initializer list or a single expression that has compatible union type.

When no designator is present, the order of initialization of union members is simply the first union member. A designator can initialize any union member.

The type of the initialized member of a union determines what rules of initialization are applied. For example, if the initialized member is a scalar object, the rule of initialization for a scalar object is applied.

The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified.

[edit] Example

#include <limits.h>
 
int main(void)
{
    union U1 {
        short int si;
        int        i;
        long int  li;
    } u1;                     /* initial value is indeterminate */
 
    union U2 {
        short int si;
        int        i;
        long int  li;
    } u2;                     /* static storage duration: 0 + zero-bit padding    */
 
    union U3 {
        short int si;
        int        i;
        long int  li;
    } u3 = {SHRT_MAX};        /* first member initialized */
 
    union U4 {
        short int si;
        int        i;
        long int  li;
    } u4 = {.li=LONG_MAX};   /* a designator can initialize any member */
 
    union U5 {                /* first member is a sub-array */
        int  i[5];
        char c;          
    } u5 = { {1,2,3,4,5} };
 
    union U6 {                /* first member is a sub-structure */
        struct s {
               char c;
               int i;
        } ss;
        char c;          
    } u6 = { {'a',1} };
 
    union U7 {                /* first member is a sub-union */
        union u {
               char c;
               int i;
        } uu;
        char c;          
    } u7 = { {'a'} };
 
    return 0;
}

Possible output:

(none)