Simvik

Callback with context

Invoke a callback for every set bit, passing through a user context. A medium embedded C problem (Function pointers and state machines), run and graded in…

medium · Function pointers and state machines · callbacks · void-pointer

Call fn once for each set bit of mask, from the lowest bit to the highest. Pass the bit position as the first argument and the caller's ctx pointer, unchanged, as the second.

The context pointer is how a callback reaches its own state without global variables.

Starter code

void for_each_set_bit(uint32_t mask, void (*fn)(uint8_t bit, void *ctx), void *ctx) {
  // fn(position, ctx) for every 1 bit in mask, lowest first.
}

Example tests

Positions in ascending order

for_each_set_bit(0x15, print_bit, NULL);
printf("\n");

Expected output:

0 2 4

Context is passed through

uint32_t sum = 0;
for_each_set_bit(0x80000001, add_bit, &sum);
printf("%u\n", sum);

Expected output:

31

Learn it first

More Function pointers and state machines problems