You can't - The switch
in C work only on primitive types, not strings. You can use, say, a hash table or search tree to optimize compliance, but only for 20 options that may not be worth the trouble.
What you can do to clear the code is the mapping table:
struct str2Num { char *str; int num; }; const struct str2Num registerMap[] = { { "zero", 00000 }, { "at", 00001 }, { "v0", 00010 }, { "v1", 00011 }, { NULL, 0 } };
and follow these steps:
int i; for (i = 0; registerMap[i].str != NULL; i++) { if (strcmp(registerName, registerMap[i].str) == 0) { return registerMap[i].num; } }
In fact, if you sorted the table alphabetically, you can even use bsearch()
for quick matching.
source share