A function with memory
Use a static local variable to count calls. An easy embedded C problem (Functions), run and graded in the browser.
easy · Functions · static
Putting the word static in front of a variable inside a function makes it keep its value between calls, while staying invisible to the rest of the program.
Return 1 the first time next_id is called, 2 the second time, 3 the third, and so on.
Starter code
int next_id(void) {
int id = 0;
id++;
return id;
}Example tests
Three calls in a row
printf("%d ", next_id());
printf("%d ", next_id());
printf("%d\n", next_id());Expected output:
1 2 3The first call
printf("%d\n", next_id());Expected output:
1Learn 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.
- Remember a value between calls · Keep state in a variable outside the functions.
- 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.