default initialization

From cppreference.com
< c‎ | language

Template:c/language/initialization/navbar

This is the initialization performed when a variable is constructed with no initializer.

[edit] Explanation

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 the type of the object is pointer type, it is initialized to a null pointer;
  • if the type of the object is arithmetic type, it is initialized to (positive or unsigned) zero;
  • if the object is an aggregate (array or struct), every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
  • if the object is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits.

[edit] Example

#include <stdio.h>
 
struct s {
    char c;
    int  i;
};
 
union u {
    short int si;
    int        i;
    long int  li;
};
 
int main(void)
{
    /* no initializer, automatic storage duration */
    /* initial value is indeterminate             */
    int a;
    int *p;
    int b[5];
    struct s c;
    union u d;
 
    /*  no initializer, static storage duration              */
    static int aa;         /* positive or unsigned zero      */
    static int *pp;        /* NULL                           */
    static int bb[5];      /* every member initialized       */
    static struct s cc;    /* every member initialized       */
    static union u dd;     /* first named member initialized */
 
    printf("%d\n", aa);
    printf("%d\n", bb[4]);
    printf("'%c' %d\n", cc.c,cc.i);
    printf("%hd\n", dd.si);
 
    return 0;
}

Possible output:

0
0
'' 0
0

[edit] See also

C++ documentation for default initialization