Skip to content

Instantly share code, notes, and snippets.

@dancollins
Created April 7, 2015 08:51
Show Gist options
  • Select an option

  • Save dancollins/475c99db557afb8f32df to your computer and use it in GitHub Desktop.

Select an option

Save dancollins/475c99db557afb8f32df to your computer and use it in GitHub Desktop.
Simple demo showing how X macros can be used to generate an enumeration as well as a string array mapped to that enumeration
/*
* This demo shows how preprocessor macros (formally called X macros) can be
* used to convert one list into both an enumeration and an array of strings.
* This is really useful for converting an enum value into a readable form.
*
* Dan Collins 2015
*/
#include <stdlib.h>
#include <stdio.h>
/* The list of values we want to turn into an enum and a string array */
#define LIST_OF_STATUSES \
X(STATUS_IDLE) \
X(STATUS_CONNECTING) \
X(STATUS_CONNECTED) \
X(STATUS_DISCONNECTING) \
X(STATUS_ERROR)
/* Create the enumeration */
#define X(name) name,
typedef enum {
LIST_OF_STATUSES
} status_t;
#undef X
/* Create the strings mapped to the enumeration */
#define X(name) #name,
static char *status_strings[] = {
LIST_OF_STATUSES
};
#undef X
int main(void) {
status_t s;
s = STATUS_IDLE;
while (s != STATUS_ERROR) {
switch(s) {
case STATUS_IDLE:
printf("%s\n", status_strings[s]);
s = STATUS_CONNECTING;
break;
case STATUS_CONNECTING:
printf("%s\n", status_strings[s]);
s = STATUS_CONNECTED;
break;
case STATUS_CONNECTED:
printf("%s\n", status_strings[s]);
s = STATUS_DISCONNECTING;
break;
case STATUS_DISCONNECTING:
printf("%s\n", status_strings[s]);
s = STATUS_ERROR;
break;
default:
printf("You're a wizard, Harry!\n");
s = STATUS_ERROR;
break;
}
}
printf("%s\n", status_strings[s]);
return 0;
}
@mickjc750
Copy link
Copy Markdown

mickjc750 commented Oct 12, 2022

Thanks! just what I was looking for. Only I'd rather the strings didn't include STATUS_ prefix.
Easily fixed:
Remove the STATUS_ prefix from lines 13-17, ie. X(STATUS_IDLE) to X(IDLE)

Then changing line 21 from
#define X(name) name,
to
#define X(name) STATUS_##name,

@dancollins
Copy link
Copy Markdown
Author

dancollins commented Oct 12, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment