preprocessor-toolchain · intermediate · ~15 min
Understand C file linkage and encapsulate state using static variables.
In C, global identifiers without the static storage-class specifier have external linkage, polluting the global symbol namespace and risking accidental collisions or tampering during linking. Internal linkage (static) encapsulates module state.
Implement an encapsulated monotonically increasing sequence generator using file-scoped static state:
void seq_init(uint32_t seed);
uint32_t seq_next(void);
uint32_t seq_peek(void);
void seq_reset(void);
seq_init(seed): sets current value to seed, and saves seed as the baseline.seq_next(): returns current value, and increments current value by 1.seq_peek(): returns current value without incrementing.seq_reset(): resets current value back to the saved seed.seq_init(100);
seq_next(); // returns 100
seq_peek(); // returns 101
seq_next(); // returns 101
seq_reset();
seq_peek(); // returns 100
seed: uint32_t baseline.
Returns uint32_t sequence values.
All internal state variables must have static internal linkage.
#include <stdint.h>
/* Define static internal state and API functions */
void seq_init(uint32_t seed) { (void)seed; }
uint32_t seq_next(void) { return 0; }
uint32_t seq_peek(void) { return 0; }
void seq_reset(void) {}
Omitting static on state variables; incrementing on peek instead of next.
seq_reset restores exact initial seed; overflow of uint32_t wraps naturally modulo 2^32.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.