preprocessor-toolchain · intermediate · ~15 min
Apply the X-Macro pattern to maintain coordinated lookup tables cleanly.
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.
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);
http_status_to_reason(int code): returns the matching reason phrase string literal, or "Unknown" if not found.http_reason_to_status(const char *reason): returns the matching integer status code, or -1 if reason == NULL or not found (case-sensitive).http_status_to_reason(404); // returns "Not Found"
http_reason_to_status("Internal Server Error"); // returns 500
http_status_to_reason(418); // returns "Unknown"
code: HTTP status integer; reason: string description.
Returns corresponding reason phrase or integer status.
Zero heap allocations. Case-sensitive exact matching.
#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;
}
Forgetting default fallback in switch; case sensitivity mismatches.
Unrecognized code returns Unknown; NULL reason returns -1; exact string matching.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.