cpp / beginner
Snippet
Static Variables Inside Functions
A static variable inside a function retains its value between function calls while remaining local to that function. Unlike regular local variables which are created and destroyed each time the function runs, static variables are initialized only once and persist throughout the program's lifetime. This makes them useful for tracking how many times a function has been called.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>void counter() {static int count = 0;count++;std::cout << "Count is: " << count << std::endl;}int main() {counter();counter();counter();return 0;}
Breakdown
1
static int count = 0;
Static local variable, initialized once, persists between calls
2
count++;
Increments the preserved count value each call
3
counter();
First call: count becomes 1
4
counter();
Second call: count becomes 2, not reset to 0