preprocessor-toolchain · intermediate · ~15 min

X-Macro Table Generator

Apply the X-Macro pattern to maintain coordinated lookup tables cleanly.

Challenge

The X-Macro pattern uses higher-order macro tables to maintain parallel structures (such as enums, string tables, and dispatch lookups) from a single source of truth without redundancy.

Your Task

Given the HTTP status codes definition table:

#define HTTP_STATUS_LIST(X) \
    X(200, OK, "OK") \
    X(400, BAD_REQUEST, "Bad Request") \
    X(404, NOT_FOUND, "Not Found") \
    X(500, INTERNAL_SERVER_ERROR, "Internal Server Error")

Implement lookup functions:

const char *http_status_to_reason(int code);
int http_reason_to_status(const char *reason);

Rules

  1. http_status_to_reason(int code): returns the matching reason phrase string literal, or "Unknown" if not found.
  2. http_reason_to_status(const char *reason): returns the matching integer status code, or -1 if reason == NULL or not found (case-sensitive).

Example

http_status_to_reason(404); // returns "Not Found"
http_reason_to_status("Internal Server Error"); // returns 500
http_status_to_reason(418); // returns "Unknown"

Input format

code: HTTP status integer; reason: string description.

Output format

Returns corresponding reason phrase or integer status.

Constraints

Zero heap allocations. Case-sensitive exact matching.

Starter code

#include <stddef.h>
#include <string.h>

const char *http_status_to_reason(int code) {
    (void)code;
    return "Unknown";
}

int http_reason_to_status(const char *reason) {
    (void)reason;
    return -1;
}

Common mistakes

Forgetting default fallback in switch; case sensitivity mismatches.

Edge cases to handle

Unrecognized code returns Unknown; NULL reason returns -1; exact string matching.

Background lessons

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