enum type

Hey guys , so I've been reading about enum , but I never got what's the point from it ? does programmers use it a lot ?

after reading the topic what I learned is that it used to know how many memory it should use for a variable , and it increases by 1 unless it's declared.

I'm the type of guy that loves to learn in action " apply it by making a small program to get the idea " but in the book I didn't really understand what the idea behind it ?
The point of enum is to define constant values. Its purpose is a lot like #define, but it has some advantages, like the fact that it's not a preprocessor directive and it can automatically increment the value of the constants.

For example, when you press a key on the keyboard, a numerical code representing the key is sent to your application. Since it's difficult to remember all the codes you can set up an enum that goes like this
1
2
3
4
5
6
7
8
enum keyCodes {
    KEY_A = 1,
    KEY_B, //Automatically set to 2
    //etc
    KEY_Z, //Incremented automatically to 26
    KEY_SPACE = 50, //Explicitly set to 50. 27-49 will not be used unless you say so. The next will be 51
    //etc
}

When you write code to respond to key presses you won't have if(key == 8) but if(key == KEY_H). It's a lot more readable and saves you the time of looking up which key corresponds to 8.
Enums can be used to group global constants that are also integral so they can be used easily in switches, iterations, or even in arithmetic.
Last edited on
The primary advantage of named enumerations over named integral constants is that they enforce type safety.

1
2
3
4
5
6
7
8
9
10
11
12
13
enum colour { RED = 1, GREEN = 2, BLUE = 4 /* ... */ } ;

enum month { JAN = 1, FEB, MAR, APR = 4  /* ... */, DEC } ;

colour clr_sky = BLUE ; // fine

clr_sky = APR ; // *** error: APR is not the same as BLUE

void print( colour clr ) { /* print the name of the colour */ } // overload one

void print( month m ) { /* print the name of the month */ } // overload two

void print( int i ) { /* print the value of the integer */ } // overload three 

Thank you guys , you helped a lot ^^
Topic archived. No new replies allowed.