1

I have

enum Direction { NONE = 0, LEFT, RIGHT, FORWARD };

and there is a function

void displayDirection(int dir)
{ ... }

This function will take an int value and will print the members of "Direction" according to that value. How can it be possible? Thanks in advance.

ex: if dir = 0 print NONE; if dir = 1, print RIGHT; etc.

PS: I am very new at c++.

Mustafa
  • 592
  • 8
  • 17
  • Isn't this already covered on about a [dozen different questions](http://stackoverflow.com/search?q=%5Bc%2B%2B%5D+enum+int+convert) – WhozCraig Oct 29 '12 at 14:22

3 Answers3

3

you need "string" versions of them to print... e.g. char* szArray[] = { "NONE", "LEFT", "RIGHT", "FORWARD" }; then in displayDirection reference it via szArray[dir]. bounds-checking would be appropriate as well...

mark
  • 5,269
  • 2
  • 21
  • 34
2

Yes, it's possible, because enum values are, under the hood, integral types. The conversion is implicit, so you should be able to directly call

displayDirection(3);  //FORWARD 

However, I suggest changing the function signature to

void displayDirection(Direction dir)
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

If you want to print the text values, "NONE", "LEFT" etc, that is not directly possible.

In the compiled executable, the names have been optimised away and you can't get them back, just like you can't reference variables by name (like "dir" in your example).

So what you should do is put the names into your program by store them in a string array.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150