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++.

1

3 Answers 3

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...

Sign up to request clarification or add additional context in comments.

Comments

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)

5 Comments

I didnt understand how can it be possible with 1st function, what should be the inside of that function. And I want to do it by int parameter, i try to learn
@Mustafa how what can be possible?
@LuchianGrigore what should be the definition of displayDirection(3) function, i think it is impossible according to other answers
@LuchianGrigore okay, how can I print "FORWARD" when I call displayDirection(3); ?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.