liveBook · Manning

Temporary object

As explained in Modern C, Third Edition

A temporary object is an unnamed C object created for an intermediate expression or initialization and given automatic temporary lifetime.

A temporary object is an unnamed C object created implicitly while evaluating an intermediate expression or initialization. It has automatic storage duration, but unlike an ordinary local variable, its lifetime follows the temporary-use context rather than a named block variable's definition. section 13.2.2 section 17.2

A function result used as an intermediate object

struct demo { unsigned ory[1]; };\nstruct demo mem(void);\n\nprintf("mem().ory[0] is %u\\n", mem().ory[0]);\n\nThe call produces a temporary struct value, whose member can be selected immediately. The expression uses that unnamed object without storing it in a named local variable. section 13.2.2

Compound literals provide another important case. In ((T){ (X) }), the compound literal first creates a temporary object of type T and then initializes it with X. This deliberately uses initialization rules to check whether X is assignment-compatible with T; an optimizing compiler can usually remove the temporary's runtime cost. section 17.2

TAKEAWAY

  • Treat temporary objects as implicit intermediate values rather than named storage. section 13.2.2
  • Use a compound literal when initialization compatibility must be checked without retaining a named object. section 17.2
 struct demo { unsigned ory[1]; };
 struct demo mem(void);
 
 printf("mem().ory[0] is %u\n", mem().ory[0]);

Inspect the returned-struct example to see a temporary object participate directly in member access. section 13.2.2

How Modern C, Third Edition covers it

How deep it goes
Explains implicit creation and optimization, but stops short of a complete lifetime model for every temporary-expression context.
Examples
Demonstrates a returned struct accessed through mem().ory[0] and a compound literal used for macro argument checking.
What it assumes
Assumes familiarity with C expressions, function calls, structures, initialization, and compound literals.
What you can do after
Evaluate C expressions that create unnamed objects and recognize compound-literal techniques for assignment-compatibility checks.
How it connects
Connects temporary objects with automatic storage duration, function calls, compound literals, initialization, and assignment compatibility.

Also explained in

Compare how 2 books explain temporary object →

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.