Can I display the value of an enum with printf()?

后端 未结 6 842
太阳男子
太阳男子 2020-12-24 05:13

Is there a one-liner that lets me output the current value of an enum?

6条回答
  •  忘掉有多难
    2020-12-24 05:54

    As a string, no. As an integer, %d.

    Unless you count:

    static char* enumStrings[] = { /* filler 0's to get to the first value, */
                                   "enum0", "enum1", 
                                   /* filler for hole in the middle: ,0 */
                                   "enum2", "enum3", .... };
    
    ...
    
    printf("The value is %s\n", enumStrings[thevalue]);
    

    This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

提交回复
热议问题