I frequently use enum in C to access array elemnets with numerical data, e.g.
#define KEYS_MAX 1
#define FIELD_MAX 2
enum {FIELD1=0, FIELD2};
double array[KEYS_MAX][FIELD_MAX];
array[1][FIELD1] = 1.0; array[1][FIELD2] = 2.0;
I then print the data to a file in KEYS_MAX lines and FIELD_MAX columns. To know later the content of the columns I would like to print a header line.
# KEY FIELD1 FIELD2
1 1.0 2.0
I would like to have a routine which does this during runtime correctly even if I update the code by changing only enum. I.e., how can I print the header line using C-code and possibly macros using a fixed routine independent of updates of enum?
I found this: Mapping enum values to strings in C++ , but I would prefer something which would also work with the intel compiler.
You could play some preprocessor tricks. As an exmple, in GCC source tree implementation, you might get inspired by
gcc/tree.deffiles.So you might have one file, e.g.
myenum.def, with e.g. things likeThen, you might define your enum with some code like
(You might want to put
None_before the#includeabove, andLast_after it)Then you could have an enum to string converter with e.g.
and you might have a string to enum converter with e.g.
All the above is common practice, not tied to a particular compiler (it should work with
gcc,clang,tcc,iccor any C99 compliant compiler).In addition, if you have a large code base (than you can compile with a recent
gcc) in which you have hundreds ofenumand you don’t want to play such tricks for every of them, you could e.g. develop a GCC plugin or extension (in MELT for instance) to generate -using the internal representations inside GCC of your code- the similar C code just from theenumdeclarations. If you are coding a new software, or you know your software base quite well, you could replace theenumcode with similar tricks.