Skip to study material
← Question index

QUESTION 18 · Scope and Lifetime

Distinguish scope, lifetime and linkage.

5 marks

Answer in brief

Scope, lifetime and linkage answer three different questions about a declaration and its associated object.

Scope: where a name is visible

A name declared inside a block generally has block scope. Outside that scope, the same spelling cannot be used to reach that declaration. Scope is a source-code rule about names, rather than a count of seconds or function calls.

Lifetime: when an object exists

An ordinary automatic local object is associated with a particular execution of its block. A static-duration object exists throughout program execution. A function call can end the lifetime of an ordinary automatic local object while a local static object continues to exist. Allocated objects have a different lifetime managed through memory allocation, covered in Unit V.

Linkage: whether declarations identify the same entity

External linkage can connect declarations across translation units. Internal linkage connects declarations within one translation unit. A typical local variable has no linkage. Linkage is not the same as visibility: a file-scope static object has internal linkage, while a block-local static object has no linkage.

Example

In void count(void) { static int total = 0; ++total; }, the name total has block scope. Its object has static storage duration, so the value can remain after count returns. A later call uses the same object. Scope is local, but the lifetime is not limited to one call.

Why the distinction matters

Do not return a pointer to an ordinary local object that stops existing when the call ends. Do not assume that a local name always describes temporary storage. State scope, storage duration and linkage separately when comparing storage classes.

Related exam questions

Related questions in the storage classes category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q1(b) · 8 marks

    If a variable has auto storage class by default, why was the auto keyword introduced in C? Explain.

    Paper P01 · page 1
  • July 2021 · Q2(c) · 5 marks

    List and explain storage classes in C.

    Paper P04 · page 1

View this category in the exam question bank →