Explain local static variables and file-scope static declarations.
5 marks
Answer in brief
The meaning of static depends on where it is used. A local static object keeps its value across calls; a file-scope static declaration gives internal linkage.
Local static object
In static int count = 0; inside a function, count has block scope and static storage duration. It is not recreated on every call. In these C examples its initial value is established before program startup, and later calls use the same object. If no initialiser is supplied, an arithmetic static-duration object is initialised to zero.
Example trace
The first call to visit increments count from 0 to 1. The second increments the same object to 2, and the third to 3. The output is therefore 1, 2 and 3. Contrast this with an automatic count initialised to zero on every call, which would print 1 each time.
File-scope static
At file scope, static int total; defines a static-duration object with internal linkage. Other translation units cannot connect an external declaration to that entity. A static function at file scope also has internal linkage. This helps keep implementation details within one translation unit.
Uses and limitations
Local static objects can store a call count or a small amount of lasting state.
File-scope static helps avoid exporting names that other source files do not need.
Persistent shared state can make testing and repeated calls depend on earlier calls.
static does not automatically make an update thread-safe.
Important distinction
A local static object has no linkage; a file-scope static object has internal linkage. Both have static storage duration, but their scopes are different.
Flowchart
Explain local static variables and file-scope static declarations. · Download diagram
This example uses values already written in the program.
Output
1
2
3
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.