0
0
Cprogramming~10 mins

Static storage class - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Static storage class
Declare static variable
Variable stored in static memory
Function called multiple times
Variable retains value between calls
Program ends
Static variables keep their value between function calls by storing data in a fixed memory location.
Execution Sample
C
#include <stdio.h>

void counter() {
    static int count = 0;
    count++;
    printf("Count: %d\n", count);
}

int main() {
    counter(); counter(); counter();
    return 0;
}
This code shows a static variable 'count' that keeps increasing each time the function is called.
Execution Table
Call Numbercount Before IncrementActioncount After IncrementOutput
10 (initialized)count++1Count: 1
21count++2Count: 2
32count++3Count: 3
----Function calls end
💡 After 3 calls, program ends; static variable 'count' retains last value 3.
Variable Tracker
VariableStartAfter Call 1After Call 2After Call 3Final
count0 (initialized)1233
Key Moments - 2 Insights
Why does 'count' not reset to 0 on each function call?
Because 'count' is declared static, it is initialized only once and keeps its value between calls, as shown in the execution_table rows 1 to 3.
What would happen if 'count' was not static?
Without static, 'count' would be reinitialized to 0 every call, so output would always be 'Count: 1' (see execution_table for static behavior contrast).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' before the second call increments it?
A0
B1
C2
D3
💡 Hint
Check the 'count Before Increment' column for Call Number 2 in the execution_table.
At which call does 'count' become 3?
AThird call
BSecond call
CFirst call
DNever
💡 Hint
Look at the 'count After Increment' column in the execution_table.
If 'count' was not static, what would be the output on the third call?
ACount: 3
BCount: 2
CCount: 1
DNo output
💡 Hint
Refer to key_moments explanation about non-static variable behavior.
Concept Snapshot
Static storage class in C:
- Declared with 'static' keyword inside functions.
- Variable initialized only once.
- Retains value between function calls.
- Stored in static memory, not stack.
- Useful for preserving state without global variables.
Full Transcript
This visual trace shows how a static variable 'count' inside a function keeps its value between calls. Initially, 'count' is set to 0 once. Each time the function runs, 'count' increases by 1 and prints the new value. Unlike normal local variables, 'count' does not reset to 0 on each call. The execution table tracks 'count' before and after increment for each call, showing it grows from 0 to 3 over three calls. Key moments clarify why static variables behave this way and what would happen without 'static'. The quiz tests understanding of variable values at different steps. This helps beginners see how static storage class works step-by-step.