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"
isabled" : \
> #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
isabled
> 3:Unknown
>
> But the output is
> i:Enabled
> i
isabled
> i:Unknown
>
> Anybody know how I can do this in a macro?
>
> Thanks,
> Cristov
I don't think you can with a macro. Also, each
invocation of `State_String(x)' puts one copy
of the strings into the program (some compilers
may combine these, but there's no guarantee).
Will something like this do what you want (I
assume you only want to define the enum's names
only once)?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef enum
{
Unknown = 0,
Enabled = 1,
Disabled = 2
} State;
static const char * const states[] = { [Enabled] "Enabled",
[Disabled] "Disabled",
[Unknown] "Unknown" };
#define State_String(x) \
(x == Enabled || x == Disabled) ? states[ x ] : states[ Unknown
]
int
main()
{
State i;
i = Enabled;
printf("State: %d:%s\n", i, State_String(i));
i = Disabled;
printf("State: %d:%s\n", i, State_String(i));
i = Disabled + 1;
printf("State: %d:%s\n", i, State_String(i));
return 0;
}
-
Stephen