Handmade Network»Forums
8 posts
Get enum names as a string array in C/C++
Despite programming in C/C++ for quite a while this technique never occurred to me. It's still quite clunky, but I have found it useful in my latest work when loading/saving values from a file.

In one .h file, lets call it sizes.h:
1
2
3
4
5
6
7
8
#ifdef GUI_SIZE

GUI_SIZE(Background)
GUI_SIZE(Button)
GUI_SIZE(Slider)

#undef GUI_SIZE
#endif


Then in another file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#define QUOTED_EXPAND(str) #str
#define QUOTED(str) QUOTED_EXPAND(str)

enum GuiSizes {
	#define GUI_SIZE(name) GuiSizes_##name,
	#include "sizes.h"	
	GuiSizes_Count,
};

const char *guiSizeNames[GuiSizes_Count] = {
	#define GUI_SIZE(name) QUOTED(name),
	#include "sizes.h"
};


TM
13 posts
Get enum names as a string array in C/C++
If you think writing a seperate header and including it repeatedly is clunky, you can also do the following:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#ifndef X_LIST
#define X_LIST \
    X(Entry0)  \
    X(Entry1)  \
    X(Entry2)  // etc...
#endif

// usage
enum ExampleEnum {
#define X(name) name,
    X_LIST
#undef X
};
static const char* ExampleEnumStrings[] = {
#define X(name) #name,
    X_LIST
#undef X
};

The technique is called X Macro
8 posts
Get enum names as a string array in C/C++
Thanks, that's even better. Looks like I don't need the QUOTED macros either.
Dumitru Frunza
24 posts
Apprentice github.com/dfrunza/hoc
Get enum names as a string array in C/C++
Edited by Dumitru Frunza on Reason: usage links
Thanks for sharing!
Have used the technique here and here