cpp / beginner
Snippet
Static Local Variables: Preserving State
A static local variable retains its value between function calls. Unlike regular local variables which are destroyed when the function ends, static variables persist. This counter prints 1, 2, 3 across three separate calls to counter().
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>void counter() {static int callCount = 0;callCount++;std::cout << "Function called " << callCount << " times" << std::endl;}int main() {counter();counter();counter();return 0;}
Breakdown
1
static int callCount = 0;
Static variable initialized once, persists across all calls
2
callCount++;
Increments the preserved counter each time function runs