Simvik

Remember a value between calls

Keep state in a variable outside the functions. An easy embedded C problem (Functions), run and graded in the browser.

easy · Functions · global-variables · state

A variable declared inside a function is created fresh on every call. To remember something between calls, declare it outside the functions.

Implement a counter with three functions. counter_tick adds one to the count, counter_value returns it and counter_reset sets it back to zero. The count starts at zero.

Starter code

int count = 0;

void counter_tick(void) {
}

int counter_value(void) {
  return 0;
}

void counter_reset(void) {
}

Example tests

Two ticks

counter_tick();
counter_tick();
printf("%d\n", counter_value());

Expected output:

2

Starts at zero

printf("%d\n", counter_value());

Expected output:

0

Learn it first

  • Functions · Splitting a program into named pieces, passing values in and getting results back.

More Functions problems