arithmetic-type initialization

From cppreference.com
< c‎ | language

Template:c/language/initialization/navbar

This is the initialization performed when an arithmetic-type object is constructed. Arithmetic types include the type char, the signed and unsigned integer types, the enumerated types, float, double, long double, float _Complex, double _Complex, and long double _Complex.


[edit] Explanation

If an object has arithmetic type and has automatic storage duration and is not initialized explicitly, its initial value is indeterminate.

If an object has arithmetic type and has static storage duration and is not initialized explicitly, its initial value is (positive or unsigned) zero.

The initializer for an arithmetic-type object shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

[edit] Example

#include <stdio.h>
 
int main(void)
{
    int a;                /* initial value is indeterminate                     */
    static int b;         /* initial value is (positive or unsigned) zero       */
    int c = 2.5+3.4;      /* initial value is the expression (after conversion) */
    double d = 2.5+3.4;
    printf("%d\n", a);
    printf("%d\n", b);
    printf("%d\n", c);
    printf("%.1f\n", d);
 
    enum E1 {red,green,blue} e1; /* initial value is indeterminate                    */
    static enum E2 {R2,G2,B2} e2;/* initial value is (positive or unsigned) zero      */
    enum E3 {R3,G3,B3} e3=G3;    /* initial value is the expression (after conversion)*/
 
    double _Complex z1;          /* initial value is indeterminate               */
    static double _Complex z2;   /* initial value is (positive or unsigned) zero */
    double _Complex z3 = 1.0;    /* using a scalar-type initializer              */
    double _Complex z4 = {1.0};
 
    return 0;
}

Possible output:

-1499329272
0
5
5.9