liveBook · Manning

Storage duration

As explained in Modern C, Third Edition

Storage duration is the lifetime category that determines when a C object is created, exists, and is initialized or destroyed.

A local name and a static object

In the listing, the file-scope i has static storage duration and exists throughout execution. The local i defines a distinct object. Inside the if block, extern unsigned i refers to the file-scope object, so the program prints 1. section 13.2

Listing 13.2 An example of shadowing with an extern variable
#include <stdio.h> 1 

unsigned i = 1;        

int main(void) { 2 
  unsigned i = 2;        /* A new object */
  if (i) {            3 
    extern unsigned i;   /* An existing object */ 
    printf("%u\n", i);  /* prints 1 */
  } else {
    printf("%u\n", i);  /* prints 2 */
  }
}

Compare the local definition with the inner extern declaration: the same spelling does not necessarily identify the same object. section 13.2

Storage duration describes when an object’s storage exists. It is distinct from identifier visibility: a name can be shadowed while the object it identifies remains usable through a pointer. Recursive calls also have separate instances of a local variable. section 13.2 section 13.0

Storage duration affects initialization:

  • Static and thread-storage objects are initialized by default. Arithmetic members receive 0 and pointer members receive nullptr. section 13.4
  • Automatic and allocated objects must be initialized explicitly. Initializers can put variables and compound literals into a well-defined state; dynamically allocated objects can instead be initialized by assignment or an initialization function. section 13.4
  • For dynamically allocated arrays, calloc can supply zeroed storage when an all-bits-zero representation is known to be a valid initialization. Objects containing pointers or floating-point data may require assignment instead. section 13.4

TAKEAWAY: Keep visibility, storage duration, and initialization separate. A hidden identifier does not imply an unusable object, and allocated storage must be tracked and initialized systematically. section 13.2 section 13.6

How Modern C, Third Edition covers it

How deep it goes
Explains shadowing and initialization rules through examples, while pointing to deeper object-lifetime and memory-model mechanics.
Examples
Uses a shadowed local variable, an extern declaration, and initialization functions for dynamically allocated objects.
What you can do after
Evaluate object visibility and choose an initialization strategy according to storage duration.
How it connects
Connects object lifetime, scope, shadowing, linkage, dynamic allocation, and initialization.

Also explained in

Compare how 2 books explain storage duration →

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.