Static Variable in C

Level 5144 keystrokes

Uses a static local variable to keep a count between calls: it is initialized only once, so each call to counter() returns one more than the last. Three calls print 1, 2 and 3.

C code

// A function that remembers how many times it has been called
1int counter() {
// static: initialized to 0 only once and kept between calls, unlike a normal local
2 static int count = 0;
// Increases the stored count by one
3 count++;
// Returns the updated count
4 return count;
5}
6
// First call: count goes from 0 to 1, prints 1
7printf("%d\n", counter());
// Second call: the kept value grows to 2
8printf("%d\n", counter());
// Third call: prints 3
9printf("%d\n", counter());

Output

1
2
3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • (× 7
  • )× 7
  • ;× 6
  • "× 6
  • ,× 3
  • \× 3
  • %× 3
  • +× 2
  • {× 1
  • }× 1

More C examples at level 5

← C typing practice