Initializing records and aggregates
Connect braced and designated initialization to typed values, then understand compound literals, lifetimes, and C23 additions.
In this chapter8 sections
A record should begin in a meaningful state. Initializers let us choose member values and, where the rules allow, name the members explicitly. We will separate these typed starting values from later assignment and raw byte filling.
1. Initialize the parts of an aggregate
Arrays and structures are aggregate types in C terminology. A union is a separate category with its own initialization rules. Braced initializer lists can describe their nested shape. In a positional structure initializer, values follow member declaration order. Designators identify a particular member with .name or an array element with [index].
struct Point { int x; int y; int z; };
struct Point point = {.y = 5, .x = 2};
int days[4] = {[0] = 31, [3] = 30};
This C99-and-later notation names the fields instead of depending solely on their positions. Remaining integer members and elements get zero values under the partial-initialization rules. The array still has four elements; sparse initialization does not create a dictionary or make it grow on demand.
2. Typed zero is more than zero bytes
struct Options { int count; double scale; int *target; };
struct Options options = {0};
For these ordinary members, the C17 {0} initializer supplies integer zero and implicitly initializes the remaining members as required: floating zero and a null pointer. That is a type-aware language operation. It is not the same promise as memset or calloc setting every representation bit to zero. Null pointers and floating values need not have all-zero representations.
Do not confuse partial initialization with no initialization. An ordinary automatic record without an initializer does not acquire initialized member values simply because another example used braces. For a union, an initializer selects one member; omitted initialization does not create independent simultaneous values for every overlapping member. Padding questions are separate from the member values you intend to use.
3. Braces in a definition are not a general expression
In C17, struct Point p = {1, 2}; initializes a new object. A later bare p = {1, 2}; is not a valid ordinary assignment expression. A compound literal supplies an unnamed object with a specified type, allowing its value to be used in an expression:
struct Point { int x; int y; };
struct Point point = {1, 2};
point = (struct Point){.x = 7, .y = 8};
The compound literal is an object, not just a textual cast over loose values. In this assignment, its structure value is copied into the existing point. A compound literal can also supply an array for a call. The following function reads one element while that array is alive; it does not retain the pointer for later use.
#include <assert.h>
static int first(const int *values)
{
return values[0];
}
int main(void)
{
int value = first((int[]){4, 5, 6});
assert(value == 4);
return 0;
}
4. An unnamed object still has a lifetime
A plain C17 compound literal outside a function body has static storage duration. Inside a block it has automatic storage duration associated with that enclosing block, rather than lasting only for the call expression. A pointer to it is usable only while its object’s lifetime permits. Returning a pointer to an ordinary block-scope compound literal does not make the object survive that block.
5. Initialization establishes a state, not every invariant
A record can be fully initialized yet violate its intended rules: a lower bound greater than an upper bound, a count larger than capacity, or a tag inconsistent with the chosen union payload. A constructor-style function can validate relationships and report failure. The final lesson develops that interface pattern. Storage for the structure and its intended flexible payload must be allocated together with a checked total size; naming the length in an initializer does not reserve those elements.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.5p21, 6.5.2.5, 6.7.9. Stable core rules used for the C17 baseline; this is not the final ISO publication.
- WG14 N3096 — public C23 working draft: 6.5.2.5 and 6.7.10. C23 notes are separate from the C17 example checks.
Before you move on
- Aggregate initialisers set member and element starting values under their type rules.
- Designators name selected members or elements without changing the object’s layout.
- Compound literals create objects whose lifetime depends on their context and version-specific rules.
Keep these ideas separate
- Typed zero initialisation / Zero bytes
- Language-level zero values follow the type’s rules; raw zero-filled bytes are not a universal substitute for every type.
Why can a designated initializer make a record’s intended starting state clearer to a reader?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- They both repeat 1.
A partial initializer does not repeat the last explicitly supplied value.
- They are initialized to zero.
✓ Correct reasoning. The remaining aggregate elements receive the implicit initialization specified by the language.
- They must contain arbitrary uninitialized values.
This aggregate has an initializer; its omitted elements are not treated like an uninitialized automatic int.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. Follow the expanded lessons above for the connected explanations.
C99 added a handful of initialization features that make certain patterns far more expressive than the C89 alternative of listing every value positionally.
Designated Initializers
A designated initializer sets a specific struct member or array index by name or position, in any order, leaving every other element implicitly zero-initialized:
struct Point { int x, y, z; };
struct Point p = { .y = 5, .x = 2 }; /* z is implicitly 0 */
int days[12] = { [0] = 31, [1] = 28, [11] = 31 }; /* the rest default to 0 */
This is far more readable than positional initialization once a struct has more than a few members, and it survives the struct being reordered later without silently initializing the wrong field.
Compound Literals
A compound literal creates an unnamed object of a given type and value inline, without a separate variable declaration — useful for passing a one-off struct or array straight into a function call:
struct Point { int x, y, z; };
void print_point(struct Point p);
int sum(const int *arr, int n);
/* Fragment: provide definitions of print_point and sum when linking. */
void compound_examples(void) {
print_point((struct Point){ .x = 1, .y = 2, .z = 3 });
(void)sum((int[]){ 4, 8, 15, 16, 23, 42 }, 6);
}
In C17, a compound literal inside a function body has automatic storage duration associated with its enclosing block; its object's lifetime ends when that block's execution ends. A compound literal outside function bodies has static storage duration. C23 additionally permits certain storage-class specifiers, such as static, so a block-scope compound literal need not have automatic storage duration.
Flexible Array Members
A flexible array member is an incomplete array as the last member of a structure with at least one other named member. It contributes no ordinary element storage to sizeof(struct Buffer), although trailing padding may exist. After a checked allocation of sizeof *b + n, at least n bytes are available for data; use length as the logical bound, not an assumed total layout or an n-byte string. If a null-terminated string of length n is needed, also reserve and check space for its terminator. Free the enclosing allocation, not data separately.
#include <stdint.h>
#include <stdlib.h>
struct Buffer {
size_t length;
char data[]; /* last member; length is another named member */
};
struct Buffer *make_buffer(size_t n) {
if (n > SIZE_MAX - sizeof(struct Buffer)) return NULL;
struct Buffer *b = malloc(sizeof *b + n);
if (b != NULL) b->length = n;
return b; /* caller checks NULL and eventually calls free */
}
Allocating sizeof(struct Buffer) + n bytes gives data at least n usable bytes within the same allocation, with no separate pointer member or second allocation required. Padding can make the available storage larger; the recorded length remains the logical bound. This standardized C99 pattern replaced the older, non-portable "struct hack" of declaring the trailing array with a fake size of 1 or 0.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.