Mustafa
Mustafa

Reputation: 590

accessing enum members by int values

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

Answers (3)

Mr Lister
Mr Lister

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

Luchian Grigore
Luchian Grigore

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

mark
mark

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

Related Questions