Reputation: 590
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++.
Upvotes: 1
Views: 638
Reputation: 46549
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.
Upvotes: 0
Reputation: 258568
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)
Upvotes: 2
Reputation: 5459
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...
Upvotes: 3