← 🧠 Storage Classes, Scope & Memory
Subtopic 1 of 5

6.1Storage classes: auto, register, static, extern

The idea

A static local variable is created once and keeps its value between calls. An ordinary (auto) local is created fresh each call.

Think of it like this: An auto variable is a whiteboard wiped clean on every visit; a static variable is a notebook that remembers what you wrote last time.

Why it exists

Counters hidden inside functions are the commonest way to make a program's output differ from the naive reading.

How it works

  1. A static local's initialiser runs only the first time.
  2. Its value persists across calls (it lives for the whole program).
  3. auto and register locals are reinitialised on every call.
  4. A global is visible everywhere; a static global only in its own file.

Worked example: total() with static count (GATE 2017)

count accumulates the number of 1 bits across calls: total(5) = 2, total(4) = 3, total(3) = 5, total(2) = 6, total(1) = 7. x = 2 + 3 + 5 + 6 + 7 = 23.

Now play with it

  • →Run auto versus static: a is always 1, s counts 1, 2, 3.
  • →Step through the GATE 2012 programs and see static a keep its value.

a is created fresh on every call and reset to 0. s is created once and keeps its value from call to call.

step 1 of 20
1#include <stdio.h>
2void f() {
3 int a = 0;
4 static int s = 0;
5 a++;
6 s++;
7 printf("a=%d s=%d\n", a, s);
8}
9int main() {
10 f();
11 f();
12 f();
13 return 0;
14}

The gold line is the statement about to run.

Call stack (top first)
main()
no variables yet
Output

Check yourself

void f() { static int n = 0; n++; printf("%d", n); } Calling f() three times prints

Remember: static = one copy, initialised once, value persists; auto = fresh on every call.
Exam notes (the dense version)

auto (the default for locals): created on entry to the block, destroyed on exit, new value every call. register: a hint to use a CPU register (you cannot take its address). static local: created once, initialised once (to 0 by default), and keeps its value between calls. extern: declares a global defined elsewhere. A static global is visible only in its own file.

Previous year questions: Storage Classes, Scope & Memory (8)

PYQs are grouped by topic, so this is the full set for Storage Classes, Scope & Memory; try the ones that match this subtopic. Open all 8 on the topic page.