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

Enumeration

I don't fully understand what kind of situation which i have to use enumeration? Something likes code below i know the concept but dunno how2 use it enum Direction {North, East, South, West}; Direction myDirection; myDirection = Direction.North; Direction ReverseDirection (Direction dir) { if(dir == Direction.North) dir = Direction.South; else if(dir == Direction.South) dir = Direction.North; else if(dir == Direction.East) dir = Direction.West; else if(dir == Direction.West) dir = Direction.East; }

28th Dec 2017, 12:38 PM
Elvin Auresius
Elvin Auresius - avatar
2 Answers
+ 1
Imo enumerated constants (enums) are a way to help make the code readable, like in your example above, if we used the value of the constant directly e.g. 0,1,2,3 then the code probably would not be as easily readable or understood than if we compare it with its symbol (North, East, South, West). Other than that we can also use enums as function parameters, e.g. to simplify an option for the function behavior or something like that. Hth, cmiiw
28th Dec 2017, 2:11 PM
Ipang
0
whenever you have a fixed and comprehensible set of manifestations you should use enumeration. you can also use an other datatype in exchange (short, int) but this would be much more error phrone and less descriptive. in the direction example you posted above you can also use the values from 0 to 3 but that would be much harder to read and implement. moreover enumeration are a restrictive set of predefined labels which helps to reduce error checking when e.g. passing them in a routine. in your case you only have 4 different manifestations and don't have to care on other values e.g. with short you have to consider values which are not in your intended range.
28th Dec 2017, 1:46 PM
thex
thex - avatar