简体   繁体   中英

How to declare strings in enum in C

typedef enum testCaseId { "TC-HIW-0019" = 0,
"TC-HIW-0020", "TC-HIW-0021"
} testCaseId;

I need my test cases to be represented in enum. In my test function, I need to switch between the test cases like:

void testfunc(uint8_t no)
{  
    switch(no)
    {
        case 0:
        case 1:
        default:
    }
}

So can anyone help on how to use enum to declare strings.

Actually, that can't be done. You can emulate it with something like the following:

typedef enum testCaseId {
    TC_HIW_0019 = 0,
    TC_HIW_0020,
    TC_HIW_0021
} testCaseId;
char *testCaseDesc[] = {
    "TC-HIW-0019",
    "TC-HIW-0020",
    "TC-HIW-0021"
};

Then you use the enumerated values ( x ) for all your code and, when you want the string value for descriptive purposes such as logging, use testCaseDesc[x] .

Just make sure you keep your enumeration and array synchronised.

Adding to Pax's solution, if you have a very large list of these things, it may be simpler to keep things together and synchronized if you use X-Macros . They're a bit hackish, but when used judiciously, they can really save you a lot of housekeeping.

#define X_TEST_CASE_LIST \
    X(TC_HIW_0019, 0, "TC_HIW_0019") \
    X(TC_HIW_0020, 1, "TC_HIW_0020") \
    X(TC_HIW_0021, 2, "TC_HIW_0021") \
    /* ... */

#define X(id, val, str) id = val,
typedef enum testCaseId {
    X_TEST_CASE_LIST
} testCaseId;
#undef X

#define X(id, val, str) str,
char *testCaseDesc[] = {
    X_TEST_CASE_LIST
};
#undef X

This can also enable some more complicated mapping behaviors. For example, you can easily implement a linear search to do a reverse mapping from string to enum value:

int string_to_enum(const char *in_str) {
    if (0)
#define X(id, val, str) else if (0 == strcmp(in_str, str)) return val;
    X_TEST_CASE_LIST
#undef X
    return -1; /* Not found */
}

PaxDiablo's solution is a good one, though a good way to help keep your enums and arrays synchronised is to add an enum value at the end of the list such as TC_MAX. Then you set the array size to be TC_MAX in size. This way if you add or remove an enum but don't update the array the compiler will complain that there aren't enough/too many initialisers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM