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

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

    There is definitely a way to do this -- use X() macros. These macros use the C preprocessor to construct enums, arrays and code blocks from a list of source data. You only need to add new items to the #define containing the X() macro. The switch statement would expand automatically.

    Your example can be written as follows:

     // Source data -- Enum, String
     #define X_NUMBERS \
        X(ONE,   "one") \
        X(TWO,   "two") \
        X(THREE, "three")
    
     ...
    
     // Use preprocessor to create the Enum
     typedef enum {
      #define X(Enum, String)       Enum,
       X_NUMBERS
      #undef X
     } Numbers;
    
     ...
    
     // Use Preprocessor to expand data into switch statement cases
     switch(num)
     {
     #define X(Enum, String) \
         case Enum:  strcpy(num_str, String); break;
     X_NUMBERS
     #undef X
    
         default: return 0; break;
     }
     return 1;
    

    There are more efficient ways (i.e. using X Macros to create an string array and enum index), but this is the simplest demo.

提交回复
热议问题