Print text instead of value from C enum

前端 未结 12 1004
借酒劲吻你
借酒劲吻你 2020-12-02 05:50
int main()
{

  enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};

  Days TheDay;

  int j = 0;

  printf(\"Please enter the day of the week (0 to         


        
12条回答
  •  萌比男神i
    2020-12-02 06:33

    I know I am late to the party, but how about this?

    const char* dayNames[] = { [Sunday] = "Sunday", [Monday] = "Monday", /*and so on*/ };
    printf("%s", dayNames[Sunday]); // prints "Sunday"
    

    This way, you do not have to manually keep the enum and the char* array in sync. If you are like me, chances are that you will later change the enum, and the char* array will print invalid strings. This may not be a feature universally supported. But afaik, most of the mordern day C compilers support this designated initialier style.

    You can read more about designated initializers here.

提交回复
热议问题