enum eDirection | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

enum eDirection

hi, I'm learning c++, I recently saw a tutorial about snake game. I just have a question that can someone explain about enum and eDirection dir? enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN }; eDirecton dir;

27th Nov 2017, 2:37 PM
Light
Light - avatar
3 Answers
+ 3
I think of enums as a way to make your code sound more like english. To answer your other questions: enum eDirection is declaring an enumeration called eDirection, which essentially becomes a new type. eDirection dir; is saying "a variable of type eDirection", which can either be STOP, LEFT, RIGHT, UP, or DOWN. I'm assuming the enumeration was defined in a class already, so that it can be referenced later using that class, so you can define the eDirection variable like this: dir = MyClass::eDirection::LEFT; I tend to make my enumerations separate like this: enum class eDirection {STOP = 0, ... }; eDirection direction = eDirection::UP; This way, I can access the enumeration directly outside of the class. As an example, you can use an enumeration in a Rock, Paper, Scissors code to define the choices the player and computer make. I think I made one of those at some point, so check out my codes (you might have to scroll a while) and use it for an example. Happy Coding!
27th Nov 2017, 11:19 PM
Zeke Williams
Zeke Williams - avatar
+ 4
enum is just a way of sorting data. each element in an enum is assigned an integer. each element is assigned an integer that is 1 greater than the integer assigned to the previous element, unless otherwise specified. for example: enum colors {blue = 0, green, red, yellow = 9, grey, purple} blue is assigned the integer 0, green is 1, red is 2, yellow is 9 because its value was specified, grey is 10 (because yellow was 9) and purple is 11. enums are very useful when you have a large amount of data that is converted into another type of data, like integers. if you have a set of directions, like in your game, when testing for a certain direction, instead of having: if direction = <some integer> you can have: if direction = <enum name>.<enum element> don't forget that it must be converted to type int beforehand, though.
27th Nov 2017, 2:49 PM
🐙evil octopus
🐙evil octopus - avatar
+ 3
Thanks for your both answers. <3 Happy coding.
28th Nov 2017, 2:14 PM
Light
Light - avatar