#cprogramminglanguage #clanguage

Compiler Explorer - C
typedef enum { THING_INVALID = -1, #define THING(X) THING_ ## X, //#include "thingdefs.h" // start of thingdefs.h #ifndef THING #error "Missing function-like macro definition" #endif THING(apple) THING(banana) THING(orange) #undef THING // end of thingdefs.h } thing_t; static const char *const dict[] = { #define THING(X) #X, //#include "thingdefs.h" // start of thingdefs.h #ifndef THING #error "Missing function-like macro definition" #endif THING(apple) THING(banana) THING(orange) #undef THING // end of thingdefs.h }; static int compare_strings(const void *const key, const void *const elemp) { assert(key); assert(elemp); const char *const *const stringp = elemp; return strcmp(key, *stringp); } thing_t string_to_id(const char *const key) { char const *prev = ""; for (size_t i = 0; i < _Countof dict; ++i) { char const *const elem = dict[i]; assert(strcmp(prev, elem) < 0); prev = elem; } (void)prev; const char *const *const elemp = bsearch(key, dict, _Countof dict, sizeof dict[0], compare_strings); if (elemp) { return (thing_t)(elemp - dict); } else { return THING_INVALID; } } int main(const int argc, const char *const argv[const static argc + 1]) { for (size_t i = 0; i < argc; ++i) { thing_t const t = string_to_id(argv[i]); switch (t) { case THING_apple: puts("Crunch!"); break; case THING_banana: puts("Squish!"); break; case THING_orange: puts("Splatter!"); break; case THING_INVALID: fputs("Invalid argument", stderr); break; } } return 0; }





