Namespaces
Variants
Views
Actions

Initialization

From cppreference.com
< c‎ | language
Revision as of 13:48, 30 December 2014 by Cubbi (Talk | contribs)

A declaraton of an object may provides its initial value through the process known as initialization.

For each declarator, the initializer, if not omitted, may be one of the following:

expression (1)
{ initializer-list } (2)

Where initializer-list is a non-empty comma-separated list of initializers (with an optional trailing comma), where each initializer has one of three possible forms:

expression (1)
{ initializer-list } (2)
designator-list = initializer (3)

Where designator-list is a list of either array designators of the form [ constant-expression ] or struct/union member designators of the form . identifier; see array initialization and struct initialization

Contents

Explanation

The initializer specifies the initial value stored in an object.

If an initializer is provided, see

If an initializer is not provided,

  • pointers are initialized to null pointer values of their types
  • objects of integral types are initialized to unsigned zero
  • objects of real types are initialized to positive zero
  • members of arrays, structs, and unions are initialized as described above, recursively, and all padding bits are initialized to zero

Notes

When initializing an object of static or thread-local storage duration, every expression in the initializer must be a constant expression or string literal.

Initializers cannot be used in declarations of objects of incomplete type, VLAs, and block-scope objects with linkage.

The initial values of function parameters are established as if by assignment from the arguments of a function call, rather than by initialization.

Example

{{example

| code= 

int a[2]; // initializes a to {0, 0} int main(void) {

   // initializes n to 1
   int n = 1;
   // initializes int x[3] to 1,2,3
   // initializes int* p to &x[0]
   int x[] = { 1, 3, 5 }, *p = x;
   // initialize w (an array of two structs) to
   // { {{1,0,0}, 0}, {{2,0,0}, 0} }
   struct {int a[3], b;} w[] = {[0].a = {1}, [1].a[0] = 2};

} }}

See also

C++ documentation for initialization