liveBook · Manning

Initializer

As explained in Modern C, Third Edition

An initializer is C syntax that supplies an initial value for an object declared in source code.

An initializer is C syntax that augments a declaration with an initial value for an object. A declaration names the kind of object an identifier refers to; a definition provides storage, and an object definition with an initializer does both. For scalar types, the initializer is an expression convertible to the object’s type, optionally enclosed in braces. section 2.3 section 5.5

Scalar and designated array initialization

double a = 7.8; double b = 2 * a; double A[5] = { [0] = 9.0, [1] = 2.9, [4] = 3.E+25, [3] = .00007, }; The designated entries select array indices explicitly. The missing element A[2] is initialized to 0.0, and indexing begins at zero. section 2.3 section 5.5

Use initializer forms according to the object being defined:

  • Initialize scalar objects with a convertible expression, such as 7.8 or 2 * a. section 5.5
  • Initialize arrays and other aggregate data with brace-enclosed lists; prefer designated initializers because explicit positions remain robust when declarations change. section 5.5
  • Use {} as the default initializer for any object in C23; before C23, {0} was required for this general form. section 5.5
  • Remember that static- and thread-storage objects receive default initialization, while automatic and allocated objects require explicit initialization. section 13.4
double A[5] = {                                      
   [0] = 9.0,                                         
   [1] = 2.9,
   [4] = 3.E+25,                                      
   [3] = .00007,                                      
 };

Inspect a complete designated initializer for a five-element array, including explicit indices, omitted elements, and floating-point values. section 2.3

How Modern C, Third Edition covers it

How deep it goes
Explains scalar, aggregate, designated, default, incomplete-array, and storage-duration rules, but defers deeper initialization-function API details.
Examples
Uses scalar assignments, designated five-element arrays, incomplete arrays, and initialization functions for dynamically allocated rational values.
What it assumes
Assumes basic C declarations and objects while clarifying the distinction between declarations, definitions, identifiers, and storage.
What you can do after
Apply initializers to define scalars and aggregates, select array elements explicitly, and choose initialization based on storage duration.
How it connects
Connects initializers with declarations, definitions, arrays, aggregate data types, storage duration, variable-length arrays, malloc, and calloc.

Also explained in

Compare how 9 books explain initializer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.