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:
2Starts at zero
printf("%d\n", counter_value());Expected output:
0Learn it first
- Functions · Splitting a program into named pieces, passing values in and getting results back.
More Functions problems
- Build on a helper · Write one function and use it inside another.
- Return true or false · Write a function that answers a yes-or-no question.
- A function with memory · Use a static local variable to count calls.
- Declare before use · Fix code that calls functions the compiler has not seen yet.
- Leap year · Turn a rule with exceptions into a logical expression.
- Distance between two values · Reuse a helper to keep the main function simple.