preprocessor-toolchain · intermediate · ~15 min

Internal Static Linkage Encapsulation

Understand C file linkage and encapsulate state using static variables.

Challenge

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.

Your Task

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);

Rules

  1. Maintain an internal static current value (initialized to 0) and an internal static seed.
  2. seq_init(seed): sets current value to seed, and saves seed as the baseline.
  3. seq_next(): returns current value, and increments current value by 1.
  4. seq_peek(): returns current value without incrementing.
  5. seq_reset(): resets current value back to the saved seed.

Example

seq_init(100);
seq_next(); // returns 100
seq_peek(); // returns 101
seq_next(); // returns 101
seq_reset();
seq_peek(); // returns 100

Input format

seed: uint32_t baseline.

Output format

Returns uint32_t sequence values.

Constraints

All internal state variables must have static internal linkage.

Starter code

#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) {}

Common mistakes

Omitting static on state variables; incrementing on peek instead of next.

Edge cases to handle

seq_reset restores exact initial seed; overflow of uint32_t wraps naturally modulo 2^32.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.