Easy way to use variables of enum types as string in C?

前端 未结 19 2470
太阳男子
太阳男子 2020-11-22 08:47

Here\'s what I am trying to do:

typedef enum { ONE, TWO, THREE } Numbers;

I am trying to write a function that would do a switch case sim

19条回答
  •  清歌不尽
    2020-11-22 09:06

    C or C++ does not provide this functionality, although I've needed it often.

    The following code works, although it's best suited for non-sparse enums.

    typedef enum { ONE, TWO, THREE } Numbers;
    char *strNumbers[] = {"one","two","three"};
    printf ("Value for TWO is %s\n",strNumbers[TWO]);
    

    By non-sparse, I mean not of the form

    typedef enum { ONE, FOUR_THOUSAND = 4000 } Numbers;
    

    since that has huge gaps in it.

    The advantage of this method is that it put the definitions of the enums and strings near each other; having a switch statement in a function spearates them. This means you're less likely to change one without the other.

提交回复
热议问题