Simvik

Describe a tagged union

Format a message whose payload type depends on a tag. A medium embedded C problem (Structs, unions and memory layout), run and graded in the browser.

medium · Structs, unions and memory layout · unions · enums · formatting

A message queue carries message_t values. The type tag says which member of the union is valid.

Write a description of m into out (a buffer of size bytes) in one of these forms:

  • TEMP 23.5 (temperature in degrees with one decimal; -5 tenths is TEMP -0.5)
  • BUTTON 2 down or BUTTON 2 up
  • TEXT hello
  • UNKNOWN for any other tag

Starter code

void describe(const message_t *m, char *out, size_t size) {
  // Switch on m->type and read only the matching union member.
  snprintf(out, size, "UNKNOWN");
}

Example tests

Temperature

message_t m = { .type = MSG_TEMP, .data.temp_tenths = 235 };
char out[24];
describe(&m, out, sizeof out);
printf("%s\n", out);

Expected output:

TEMP 23.5

Button

message_t m = { .type = MSG_BUTTON, .data.button = { 2, true } };
char out[24];
describe(&m, out, sizeof out);
printf("%s\n", out);

Expected output:

BUTTON 2 down

Learn it first

More Structs, unions and memory layout problems