Re: Macro to stringify an enum

From: Eric Sosman (Eric.Sosman_at_sun.com)
Date: 06/02/04


Date: Wed, 02 Jun 2004 15:54:07 -0400

Chris wrote:
> This is what I want to do, I have enum and I want to turn it into a
> string using the number I've assigned to and concatenting a string to
> the end of it or displaying some error string for invalid enums.
>
> typedef enum
> {
> Enabled = 1,
> Disabled = 2
> } State;
>
> #define State_String(x) (\
> (x == Enabled) ? #x":Enabled" : \
> (x == Disabled) ? #x":Disabled" : \
> #x":Unknown")
>
> int main()
> {
> int i;
>
> i = Enabled;
> printf("State: %s", State_String(i));
> i = Disabled;
> printf("State: %s", State_String(i));
> i = Disabled + 1;
> printf("State: %s", State_String(i));
>
> return 0;
> }
>
> I want the output to look like
> 1:Enabled
> 2:Disabled
> 3:Unknown
>
> But the output is
> i:Enabled
> i:Disabled
> i:Unknown
>
> Anybody know how I can do this in a macro?

     It cannot be done by a macro that generates a string
literal, because the string literal's contents are fixed
at compile time. The variable `i' takes on different
values as the program progresses, and the string literal
cannot change to reflect the changes in `i'.

     If you are willing to change your printf() format
the problem can be solved:

        #define STATE(x) (\
            ((x) == Enabled ? "Enabled" : \
            ((x) == Disabled ? "Disabled" : \
                             ? "Unknown")
        ...
        printf ("State: %d:%s\n", i, STATE(i));

     Why insist on a macro, though? Do you have a special
reason not to use an ordinary function?

-- 
Eric.Sosman@sun.com


Relevant Pages

  • Re: enums: What the H? again
    ... > find no sign of it in the Enum class until I did a decompile and saw ... > private String shortName; ... > private static InDir currentState = UNKNOWN; ...
    (comp.lang.java.programmer)
  • Re: enums: What the H? again
    ... Everything comes clear when you decompile an enum, ... private String shortName; ... private static InDir currentState = UNKNOWN; ...
    (comp.lang.java.programmer)
  • Re: Help with class definition for a beginner
    ... Or declare the enum globally and use like so: ... Funny thing is that I had to change the return type of getSizeto int to ... virtual string getDescription; ...
    (microsoft.public.vc.language)
  • Re: Piped delimited string to int
    ... You can just pipe the enums together and cast the enum to int whenever you ... string and it is int32 hexadecimal format. ...
    (microsoft.public.dotnet.languages.csharp)
  • A Class to get the name of Enum constant at runtime
    ... Dim rs As ADODB.Recordset ... You can get the description of an Enum form it's value. ... EnumName As String, ... Dim Idx As Long ...
    (microsoft.public.vb.general.discussion)