Reputation: 335
Is their a simple way to initialize a typedef enum to a string in C? For example, I would like to initialize the following typedef enum to its string counterpart:
typedef enum
{
ADD,
PLUS, MINUS, MUL, DIV, MOD,
AND, OR, NOT,
BROKEN_FOO
} foo;
Just like how one initializes any string in C (char* foo = "+"
), how could I initialize each member of foo to its string counterpart? e.g. MINUS = "-" etc. I know that each member is represented as an int, but I'm not sure how to go about this, given that each member is represented as an int.
Upvotes: 1
Views: 1801
Reputation: 1922
An alternative that ensures that the symbol aligns with the enum
,
#include <stdio.h>
#define OPS \
X(ADD, +), \
X(PLUS, +), \
X(MINUS, -), \
X(MUL, *), \
X(DIV, /), \
X(MOD, %), \
X(AND, &), \
X(OR, |), \
X(NOT, ^)
#define X(a, b) a
enum Foo { OPS };
#undef X
#define X(a, b) #b
static const char *const foo_strings[] = { OPS };
#undef X
static const unsigned foo_size = sizeof foo_strings / sizeof *foo_strings;
#define X(a, b) #a
static const char *const foo_title[] = { OPS };
#undef X
int main(void) {
unsigned foo;
for(foo = 0; foo < foo_size; foo++)
printf("%s: %s\n", foo_title[foo], foo_strings[foo]);
printf("DIV: %s.\n", foo_strings[DIV]);
return 0;
}
Upvotes: 2
Reputation: 35154
Enums are represented as integral values, so you cannot assign values of type char*
.
You could, however, maintain a separate array of strings corresponding to the enum-values:
typedef enum
{
ADD = 0,
PLUS = 1, MINUS = 2, MUL = 3, DIV = 4, MOD = 5,
AND = 6, OR = 7, NOT = 8,
BROKEN_FOO = 9
} foo;
const char* fooStrings[] = {
"+","+","-","*","/","%","&","|","^",NULL
};
int main() {
printf("OR (%d): %s\n", OR, fooStrings[OR]);
}
Upvotes: 2