Two storage classes remain. static gives a local variable a memory that survives between calls, which is useful for counters and “has this run before?” flags. register is a historical hint for speed that still appears in examinations.
Static local variables
Properties of a static variable:
Scope: local, like an automatic variable; other functions cannot use its name.
Lifetime: the whole program run.
Initialisation: done only once, before the program starts, and the initial value must be a constant expression. Without an initialiser, it starts at 0.
Register variables
A CPU register is a very small, very fast storage location inside the processor. The register storage class asks the compiler to keep a heavily used local variable in a register instead of main memory:
Syntax
register int i;
Property
Register variable
Scope and lifetime
Same as an automatic variable
Default initial value
Garbage
Address
The & operator cannot be applied, so no pointer to it
Guarantee
None: it is only a request, and the compiler may ignore it
Typical use
Loop counters
Comparison of the four storage classes
Feature
auto
extern (global)
static (local)
register
Declared
Inside a block
Outside all functions
Inside a block with static
Inside a block with register
Scope
Block
File (program)
Block
Block
Lifetime
Block execution
Whole program
Whole program
Block execution
Default value
Garbage
0
0
Garbage
Keeps value between calls
No
Yes
Yes
No
& allowed
Yes
Yes
Yes
No
Key takeaways
static local variables: local scope, whole-program lifetime, initialised once, default 0.
They are used for values that must persist between calls, such as counters.
register requests fast storage; it is a hint, and & cannot be used on such a variable.
auto and register variables start as garbage; extern and static variables start at 0.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a function next_id that returns 101 on its first call, 102 on its second, and so on, without using a global variable. Explain why it works.
Show worked answer
int next_id(void) { static int id = 100; id++; return id; }. The variable id is static, so it is created and set to 100 once only. Each call adds 1 and returns the new value: the first call returns 101, the second finds id still 101 and returns 102, and so on. Because id is local, no other function can change it accidentally, which is the advantage over a global variable.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions/static-and-register-variables/ to read this page.