handmade.network » Forums » Get enum names as a string array in C/C++
sam_windell
7 posts
#13059 Get enum names as a string array in C/C++
2 months, 1 week ago

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"
};


Cranky
TM
12 posts
#13060 Get enum names as a string array in C/C++
2 months, 1 week ago

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
sam_windell
7 posts
#13061 Get enum names as a string array in C/C++
2 months, 1 week ago

Thanks, that's even better. Looks like I don't need the QUOTED macros either.
dfrunza
Dumitru Frunza
21 posts

Apprentice
github.com/dfrunza/hoc

#13063 Get enum names as a string array in C/C++
2 months, 1 week ago Edited by Dumitru Frunza on Sept. 11, 2017, 4:35 p.m. Reason: usage links

Thanks for sharing!
Have used the technique here and here

Programming is hard, let's go shopping!