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

前端 未结 19 2038
太阳男子
太阳男子 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 08:55

    Try Converting C++ enums to strings. The comments have improvements that solve the problem when enum items have arbitrary values.

    0 讨论(0)
  • 2020-11-22 08:58

    There's no built-in solution. The easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse enum (one that doesn't start at 0 or has gaps in the numbering) where some of the int mappings are high enough to make an array-based mapping impractical then you could use a hash table instead.

    0 讨论(0)
  • 2020-11-22 09:00
    #define stringify( name ) # name
    
    enum MyEnum {
        ENUMVAL1
    };
    ...stuff...
    
    stringify(EnumName::ENUMVAL1);  // Returns MyEnum::ENUMVAL1
    

    Further discussion on this method

    Preprocessor directive tricks for newcomers

    0 讨论(0)
  • 2020-11-22 09:01
    // Define your enumeration like this (in say numbers.h);
    ENUM_BEGIN( Numbers )
        ENUM(ONE),
        ENUM(TWO),
        ENUM(FOUR)
    ENUM_END( Numbers )
    
    // The macros are defined in a more fundamental .h file (say defs.h);
    #define ENUM_BEGIN(typ) enum typ {
    #define ENUM(nam) nam
    #define ENUM_END(typ) };
    
    // Now in one and only one .c file, redefine the ENUM macros and reinclude
    //  the numbers.h file to build a string table
    #undef ENUM_BEGIN
    #undef ENUM
    #undef ENUM_END
    #define ENUM_BEGIN(typ) const char * typ ## _name_table [] = {
    #define ENUM(nam) #nam
    #define ENUM_END(typ) };
    #undef NUMBERS_H_INCLUDED   // whatever you need to do to enable reinclusion
    #include "numbers.h"
    
    // Now you can do exactly what you want to do, with no retyping, and for any
    //  number of enumerated types defined with the ENUM macro family
    //  Your code follows;
    char num_str[10];
    int process_numbers_str(Numbers num) {
      switch(num) {
        case ONE:
        case TWO:
        case THREE:
        {
          strcpy(num_str, Numbers_name_table[num]); // eg TWO -> "TWO"
        } break;
        default:
          return 0; //no match
      return 1;
    }
    
    // Sweet no ? After being frustrated by this for years, I finally came up
    //  with this solution for my most recent project and plan to reuse the idea
    //  forever
    
    0 讨论(0)
  • 2020-11-22 09:05

    I know you have a couple good solid answers, but do you know about the # operator in the C preprocessor?

    It lets you do this:

    #define MACROSTR(k) #k
    
    typedef enum {
        kZero,
        kOne,
        kTwo,
        kThree
    } kConst;
    
    static char *kConstStr[] = {
        MACROSTR(kZero),
        MACROSTR(kOne),
        MACROSTR(kTwo),
        MACROSTR(kThree)
    };
    
    static void kConstPrinter(kConst k)
    {
        printf("%s", kConstStr[k]);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题