Reputation: 251
I am a little bit confused on why Enums are important. Lets say we have the following code...
enum playerState {walking, running, idle, jumping, dead};
playerState myPlayerState = idle;
if{energy == 0}
{
myPlayerState = dead;
}
How is this more efficient than just using a string and avoiding the enumeration altogether, and switching to new appropriate string values when necessary?
string playerState = "idle";
if{energy == 0}
{
playerState = "dead";
}
Upvotes: 2
Views: 492
Reputation: 45740
The difference is an Enum defines a strict set of values that a variable can hold, and will give you a compile-time error if you try to give it something bad.
With Strings, they can take any value, and if the string is "bad" by some definition in your program, it will fail at runtime instead; or not at all, and lead to unpredictable behaviour.
Things failing at compile time are much better than them failing at runtime; when possible.
@Jeff is right too though. An Enum will take up less space pretty much always, so if you have a lot of variables floating around, using an Enum may make a difference.
Upvotes: 3
Reputation: 105
Upvotes: 1
Reputation: 2373
2 reasons:
1) In most languages the enum will be implemented using an integer or similar, which typically will take up less memory than a comparable string.
2) It is a guide for other developers looking at your code, letting them know that there is a finite list of possible states the variable can take on, and telling them what they are in natural language.
Upvotes: 2