Why enum?

enum can be used to give a "name" a value.

like

1
2
3
4
5
6
7
enum
{
    keyUp, // gives "keyUp" the value 0
    keyDown,  // gives "keyDown" the value 1
    keyLeft,  // gives "keyLeft" the value 2 
    keyRight  // gives "keyRight" the value 3
};


This can be done like this too:

1
2
3
4
int keyUp = 0;
int keyDown = 1;
int keyLeft = 2;
int keyRight = 3;


A friend told me it was because a enum value was constant, but you can do that by saying this:

1
2
3
4
const int keyUp = 0;
const int keyDown = 1;
const int keyLeft = 2;
const int keyRight = 3;


So why use enum?? except that it is less typing?
The reason why is that anyone else who looks at your code will immediately know what is going on. Second, it reduces the likelihood of mistakes when writing a long enumeration. There are probably others that I cannot think about at the moment.
so is a enum value a constant value or can it be changed as we like?
I believe it is a const, but you can always write a program to try it out.
closed account (S6k9GNh0)
Enum are a bunch of constant values that are sequenced. Enums are useful lots of places although difficult to explain. Another reason to use enum is that you can turn an enum into a type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdlib.h>

enum KEYS
{
    UP,
    RIGHT,
    DOWN,
    LEFT
};

void (KEYS enumExample)
{
    switch (enumExample)
    {
        case UP:
        case RIGHT:
        case DOWN:
        case LEFT: break;
        default: exit(1);
    }
}


This is the best example I can think of. Here we create a enum type called KEYS. We then make a function parameter with KEYS. This is good because if the developer tries to pass something that isn't inside the KEYS type, it will error out which is a good thing.
Last edited on
ohh, it became clear now. Thank you so much.
Topic archived. No new replies allowed.