Step 2 of 6
static functions and variables
static has two jobs in C, and both are about hiding:
- On a function or global variable, it means internal linkage: the name is private to its
.cfile. Other files can't call it, and two files can each have their ownstatic int helper(void)without clashing. Mark every helper that isn't part of the headerstatic. - On a local variable, it means the variable keeps its value between calls. It's created once, not every time the function runs.
static int clamp(int v) { ... } /* private helper */
int next_id(void) {
static int last = 0; /* initialized once */
return ++last;
}
Your turn: write int next_ticket(void) that returns 1, 2, 3, ... on successive calls, using a static local. Also write a private static helper pad3(int n) returning n % 1000, and use it so tickets wrap back to 0 after 999.
Previous: Headers and include guards Next: extern and shared state