How to declare strings in an enumeration in C

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

I need my test cases to be listed. In my test function, I need to switch between test cases, for example:

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

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

+3
source share
3 answers

This is actually impossible. You can emulate it as follows:

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"
};

(x) , , , , testCaseDesc[x].

, .

+8

Pax, , , X-Macros. , .

#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

. , , :

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 */
}
+6

PaxDiablo's solution is a good one, although a good way to help synchronize your enums and arrays is to add an enumeration value at the end of the list, such as TC_MAX. Then you set the size of the array to size TC_MAX. Thus, if you add or remove an enumeration, but do not update the array, the compiler will complain that there are not enough / too many initializers.

+4
source

Source: https://habr.com/ru/post/1741901/


All Articles