liveBook · Manning

Compound literal

As explained in Modern C, Third Edition

A compound literal is C syntax consisting of a type name in parentheses followed by an initializer that creates an unnamed object with the specified type and value.

The expression `(int){ 42 }` defines an unnamed object of type `int` initialized to 42. In general, a compound literal has the form `(T){ INIT }`: a type name in parentheses followed by an initializer. It defines an object, not merely a constant value. section 5.6.4

An array in a macro

A macro can replace a name with a compound literal, for example `#define NAMES (char const*const[]){ "raven", "jay" }`. An expression such as `NAMES[0]` then indexes the unnamed array. The space after the macro name matters: without it, the following parentheses would start a function-like macro definition. Do not put a terminating semicolon in the replacement. section 5.6.4

For this named-constant idiom, const qualification helps express that the object should not change. An ordinary compound literal is nevertheless not a constant in the same sense as an integer constant expression, and is not suitable where one is required. section 5.6.4

Checking assignment compatibility

The expression `((void*){ (X) })` initializes a temporary `void*` object with `X`. Initialization permits a restricted set of implicit conversions, including conversion of an object pointer to `void*`. Unlike a cast to `void*`, this gives the compiler an opportunity to check assignment compatibility. section 17.2

A pointer to a compound literal is usable only while the object is alive. A literal in a `while` statement's secondary block has a new local object on each iteration; dereferencing a saved pointer after the loop is invalid. A literal in a surrounding block repeated with `goto` instead remains alive until that block is left. section 19.3

C23 also permits `constexpr` on compound literals. It implies const qualification, and a `constexpr` initializer must fit exactly: a conversion that changes the value is an error. section 5.6.5

How Modern C, Third Edition covers it

How deep it goes
Explains syntax, macro pitfalls, assignment checks, and lifetime differences between loop iterations and goto repetition.
Examples
Uses a bird-name array macro, a pointer compatibility check, and contrasting while and goto lifetime examples.
What you can do after
Apply compound literals in macros and type checks while avoiding invalid access after an object's lifetime ends.
How it connects
Connects compound literals to macros, initializers, integer constant expressions, assignment compatibility, object lifetime, and constexpr.

Also explained in

Compare how 2 books explain compound literal →

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.