How to print enums?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kenk
    New Member
    • Nov 2006
    • 13

    How to print enums?

    Hi,

    Does enyone know how to print string describing the enum value?
    For example:

    enum MyEnum{F1=1, F2};
    ...
    MyEnum me = F2;
    printf("My Value: %d", me);
    ...
    I get string: "My Value: 2", but how can i format the string to get strong like:
    "My Value: F2" ?

    Thanks in advance for help?

    kenk
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    There is no short cut
    Code:
    if (me == F2)
    {
        printf("My Value: F2");
    }
    else if (me == F2)
    {
        printf("My Value: F1");
    }
    else
    {
        printf("My Value: Invalid Enum Value");
    }
    When using enums I often implement a function that returns const char * to convert the enum value to a string of it's name to make it easily accessable for debug messages.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      Code:
      if (me == F2)
      {
          printf("My Value: F2");
      }
      else if (me == F2)
      {
          printf("My Value: F1");
      }
      else
      {
          printf("My Value: Invalid Enum Value");
      }
      This will work, but if you want to save some typing, use a switch structure:

      Code:
      switch(me) {
         case F1: printf("My Value: F1"); break;
         case F2: printf("My Value: F2"); break;
         default: printf("My Value: Invalid Enum Value");
      }

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by Ganon11
        This will work, but if you want to save some typing, use a switch structure:
        Quite and in fact particularly true if the enum has >>>2 values

        Comment

        Working...