Re: Macro to stringify an enum
From: Eric Sosman (Eric.Sosman_at_sun.com)
Date: 06/02/04
- Next message: Stephen L.: "Re: Macro to stringify an enum"
- Previous message: James Kanze: "Re: Memory size?"
- In reply to: Chris: "Macro to stringify an enum"
- Next in thread: Chris: "Re: Macro to stringify an enum"
- Reply: Chris: "Re: Macro to stringify an enum"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Stephen L.: "Re: Macro to stringify an enum"
- Previous message: James Kanze: "Re: Memory size?"
- In reply to: Chris: "Macro to stringify an enum"
- Next in thread: Chris: "Re: Macro to stringify an enum"
- Reply: Chris: "Re: Macro to stringify an enum"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|