Printing enum name as string

Jul 15, 2008 at 4:51pm
Hi dears,

Since sometime now I am thinking how can it be made possible to convert an enum name as a string, given the enum value. This is especially useful if you use enums as error values and want to trace these out as strings.

Conside the following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
enum enMyErrorValue
{
  ERROR_INVALIDINPUT = 0,
  ERROR_NULLINPUT,
  ERROR_INPUTTOOMUCH,
  ERROR_IAMBUSY
}

//I want a function as follows
void vPrintError(enMyErrorValue enError)
{
//YOUR CODE HERE;-)
}
void main()
{
 vPrintError((enMyErrorValue)1);
}
//which should output as below

 vPrintError(enMyErrorValue enError)
"ERROR_NULLINPUT"


Hope you got my idea..

Thanks,
vinod
Jul 15, 2008 at 5:01pm
You can use the preprocessor to do that iff you explicitly name the enum. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define stringify( name ) # name

enum enMyErrorValue
  {
  ERROR_INVALIDINPUT = 0,
  ERROR_NULLINPUT,
  ERROR_INPUTTOOMUCH,
  ERROR_IAMBUSY
  };

const char* enMyErrorValueNames[] = 
  {
  stringify( ERROR_INVALIDINPUT ),
  stringify( ERROR_NULLINPUT ),
  stringify( ERROR_INPUTTOOMUCH ),
  stringify( ERROR_IAMBUSY )
  };

void vPrintError( enMyErrorValue enError )
  {
  cout << enMyErrorValueNames[ enError ] << endl;
  }

int main()
  {
  vPrintError((enMyErrorValue)1);
  }

The stringify() macro can be used to turn any text in your code into a string, but only the exact text between the parentheses. There are no variable dereferencing or macro substitutions or any other sort of thing done.

For example, you could say:
1
2
3
4
int main()
  {
  cout << stringify( Hello world! ) << endl;  // (leading and trailing whitespace is ignored)
  }


Hope this helps.
Jul 16, 2008 at 2:51am
Thanks Duoas. In this way there s an overhead in code size because of the const string array:-(

Just wondering whether there could be also another way to accomplish the goal without this overhead!
Jul 16, 2008 at 10:24am
There is no way to avoid the overhead. Somewhere in your executable there must exist the enum values as strings in order to be able to print them.
Jul 16, 2008 at 8:36pm
Instead of using an enum. Create another file called "Translations.h" or something. Inside each of them have something like

 
#define ERROR_IAMBUSY "I am busy" 


This is a common technique that is used when writing multi-language software. You put all of the strings used in your program in this file (not just errors) so the translators only have to work on 1 file to translate your application :)
Last edited on Jul 16, 2008 at 8:37pm
Topic archived. No new replies allowed.