Skip to study material
← Question index

QUESTION 24 · Storage Classes

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

  1. Local static objects can store a call count or a small amount of lasting state.
  2. File-scope static helps avoid exporting names that other source files do not need.
  3. Persistent shared state can make testing and repeated calls depend on earlier calls.
  4. 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

Control flow for static-counter with labelled true and false paths.
Explain local static variables and file-scope static declarations. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
void visit(void)
{
    static int count = 0;
    ++count;
    printf("%d\n", count);
}
int main(void)
{
    visit(); visit(); visit();
    return 0;
}

Sample input and output

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.

    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 →