3

Possible Duplicate:
Easy way to use variables of enum types as string in C?
Is this possible to customize printf?

is it possible to print own defined typedef in more convinient way? Here is example:

typedef enum {
    On,
    Off,
    Unknown
} State;

State st;

st=getState();
printf("State is:%??",st);

I want to be displayed "State is:On | Off | Unknown"

Community
  • 1
  • 1
alevins
  • 39
  • 1
  • 2

1 Answers1

0

No, but you can do a trick:

typedef enum {
    On = '\000 nO',
    Off = '\000ffO',
    Unknow = '\000knU'
} State;

int main(int argc, const char * argv[])
{
    State st;

    st = On;

    printf("state is %s",(char *)&st);


}

When you specify enum tags you can assign an integer value.

Something like 'ABCD' is a multi-character constant that result in a 32 bit value. Each byte is the ASCII value of the corresponding character.

In the above example I assigned to each tag a multi-character constant that, treated as tring instead of integer, results in a 3 character tag.

It's rather ugly. I admit. You are forced with 3 character tags and you have to write them reversed (as on Mac OS X - Intel).

But works.

Paolo
  • 15,233
  • 27
  • 70
  • 91
  • 1
    This relies on you having a little-endian processor and compiler support for multibyte 'character' literals... – nneonneo Jan 30 '13 at 20:53
  • If you're lucky enought to have big-endian you don't even have to write them reversed. If you're unlucky enought of not having support for multi-character constants it won't work. – Paolo Jan 30 '13 at 21:01
  • Multi-character character constants are standard. However, their value is implementation-defined. – Daniel Fischer Jan 30 '13 at 21:12