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

前端 未结 19 2048
太阳男子
太阳男子 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:09

    KISS. You will be doing all sorts of other switch/case things with your enums so why should printing be different? Forgetting a case in your print routine isn't a huge deal when you consider there are about 100 other places you can forget a case. Just compile -Wall, which will warn of non-exhaustive case matches. Don't use "default" because that will make the switch exhaustive and you wont get warnings. Instead, let the switch exit and deal with the default case like so...

    const char *myenum_str(myenum e)
    {
        switch(e) {
        case ONE: return "one";
        case TWO: return "two";
        }
        return "invalid";
    }
    

提交回复
热议问题