basics · intermediate · ~15 min

A counter with static state

Use static storage duration for state that persists across calls.

Challenge

Build a function that remembers how many times it has been called, using a static local.

Task

Implement int counter_next(void) that returns 1 on its first call, 2 on the next, 3 after that, and so on. Keep the count in a static local variable so it persists across calls. No main — the grader calls it.

Input

None (takes no arguments).

Output

Returns the next counter value: 1, then 2, then 3, ... on successive calls.

Example

counter_next()   ->   1     (first call)
counter_next()   ->   2
counter_next()   ->   3

Edge cases

  • The very first call returns 1, not 0.

Rules

  • Use a static local to retain state between calls.

Input format

None (no arguments).

Output format

The next counter value (1, 2, 3, ...) on each call.

Constraints

Use a static local; the first call returns 1.

Starter code

int counter_next(void) {
    /* TODO: use a static local */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.