To do this, use the designated C99 initializers, but care needs to be taken if your error codes are negative.
First version for positive values:
#define CODE(C) [C] = #C static char const*const codeArray[] = { CODE(EONE), CODE(ETWO), CODE(ETHREE), }; enum { maxCode = (sizeof codeArray/ sizeof codeArray[0]) };
An array with the required length and line pointers in the correct positions is allocated here. Note that duplicate values ββare allowed by the standard, the latter is the one that is actually stored in the array.
To print the error code, you will need to check if the index is less than maxCode
.
If your error codes are always negative, you just need to cancel the code before printing. But it's probably not bad to do the opposite: have codes positive and check the return value for your character. If this is a negative error code it will be a negation of the value.
source share