Skip to Content
Circuitera

Keep an Arduino counter across loop calls with static

An ordinary local variable initialized inside a repeatedly called function starts over each call.

0 of 3 complete · Progress saved on this device

Work out the example

An ordinary local variable initialized inside a repeatedly called function starts over each call. A local static variable has persistent storage but stays scoped to that function.

After increment() runs three times with a static counter starting at zero, what is its value?

Decide what to check next

A static value survives calls while the sketch is running. Resetting power or restarting the sketch initializes it again. Persist across power cycles only when the project deliberately chooses storage.

Compare with the serial result

The sketch prints 1, 2, 3. Resetting it starts the sequence over.

Open the exact Uno example

The sketch prints 1, 2, 3. Resetting it starts the sequence over.

void setup() {
  Serial.begin(9600);
  auto increment=[]() { static unsigned int runs=0; return ++runs; };
  Serial.println(increment());
  Serial.println(increment());
  Serial.println(increment());
}
void loop() {}

Verified with [email protected] on Uno R3 (2026-12-05 UTC). This check did not use physical hardware.

Continue learning

Sources