Enumeration

What is enum used for, and why should I use it?
Enums are use for constants, they should be used to make the code more readable.
For example:
1
2
3
4
5
6
7
enum class Keys
{
  Tab = 9,
  Space = 32
};

Keys key = Keys::Tab; // much clearer than int key = 9; 
one place I have used them a lot is to 'name' and size array (vectors).

consider a very simple example
enum colors {R,G,B,A, cmax};
vector<unsigned char> black(cmax);
cmax[R] = 0; //set the red component to zero, for example
... etc

now say 2 years later I want to add HSL conversion values to it.
all I have to do is this:
enum colors {R,G,B,A,H,S,L cmax};
and upon recompile every color in the code grew to fit the new data thanks to cmax. Its a nice way to make vectors just a little nicer for certain types of problems.
Last edited on
Topic archived. No new replies allowed.