An initializer is an optional part of a data declaration that specifies an initial value of a data object. The initializers that are legal for a particular declaration depend on the type and storage class of the object to be initialized.
The initialization properties and special requirements of each data type are described in the section for that data type.
The initializer consists of the = symbol followed by an initial expression or a brace-enclosed list of initial expressions separated by commas. Individual expressions must be separated by commas, and groups of expressions can be enclosed in braces and separated by commas. Braces ({ }) are optional if the initializer for a character string is a string literal. The number of initializers must not be greater than the number of elements to be initialized. The initial expression evaluates to the first value of the data object.
To assign a value to an arithmetic or pointer type, use the simple initializer: = expression. For example, the following data definition uses the initializer = 3 to set the initial value of group to 3:
int group = 3;
For unions, structures, and aggregate classes (classes with no constructors, base classes, virtual functions, or private or protected members), the set of initial expressions must be enclosed in braces unless the initializer is a string literal.
In an array, structure, or union initialized using a brace-enclosed initializer list, any members or subscripts that are not initialized are implicitly initialized to zero of the appropriate type.
Example
In the following example, only the first eight elements of the array grid are explicitly initialized. The remaining four elements that are not explicitly initialized are initialized as if they were explicitly initialized to zero.
static short grid[3] [4] = {0, 0, 0, 1, 0, 0, 1, 1};
The initial values of grid are:
Element | Value | Element | Value |
---|---|---|---|
grid[0] [0] | 0 | grid[1] [2] | 1 |
grid[0] [1] | 0 | grid[1] [3] | 1 |
grid[0] [2] | 0 | grid[2] [0] | 0 |
grid[0] [3] | 1 | grid[2] [1] | 0 |
grid[1] [0] | 0 | grid[2] [2] | 0 |
grid[1] [1] | 0 | grid[2] [3] | 0 |
The remainder of this section pertains to C++ only.
In C++, you can initialize variables at namespace scope with nonconstant expressions. In C, you cannot do the same at global scope.
If your code jumps over declarations that contain initializations, the compiler generates an error. For example, the following code is not valid:
goto skiplabel; // error - jumped over declaration int i = 3; // and initialization of i skiplabel: i = 4;
You can initialize classes in external, static, and automatic definitions. The initializer contains an = (equal sign) followed by a brace-enclosed, comma-separated list of values. You do not need to initialize all members of a class.
Related References