Enumeration!!!

Hi, Can someone explain what exactly the enumeration in c++ is? and how and when can I use it in my programs?

cheers
Enumerations are typed numeric constants. You can use them like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
enum E { one, two, three };
...
void func(const E e)
{
  switch(e)
  {
   case one:
    do_one();
    break;
   case two:
    do_two();
    break;
  }
}

This was taken from this websites tutorial on "Other Data Types" (I'll provide a link to it at the bottom).

cplusplus dot com wrote:
Enumerations (enum)
Enumerations create new data types to contain something different that is not limited to the values fundamental data types may take. Its form is the following:

1
2
3
4
5
6
7
enum enumeration_name {
  value1,
  value2,
  value3,
  .
  .
} object_names;

For example, we could create a new type of variable called colors_t to store colors with the following declaration:

enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

Notice that we do not include any fundamental data type in the declaration. To say it somehow, we have created a whole new data type from scratch without basing it on any other existing type. The possible values that variables of this new type color_t may take are the new constant values included within braces. For example, once the colors_t enumeration is declared the following expressions will be valid:

1
2
3
4
colors_t mycolor;
 
mycolor = blue;
if (mycolor == green) mycolor = red; 


Enumerations are type compatible with numeric variables, so their constants are always assigned an integer numerical value internally. If it is not specified, the integer value equivalent to the first possible value is equivalent to 0 and the following ones follow a +1 progression. Thus, in our data type colors_t that we have defined above, black would be equivalent to 0, blue would be equivalent to 1, green to 2, and so on.

We can explicitly specify an integer value for any of the constant values that our enumerated type can take. If the constant value that follows it is not given an integer value, it is automatically assumed the same value as the previous one plus one. For example:

1
2
3
enum months_t { january=1, february, march, april,
                may, june, july, august,
                september, october, november, december} y2k;


In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values that go from january to december and that are equivalent to values between 1 and 12 (not between 0 and 11, since we have made january equal to 1).


This information can be found at the bottom of this page: http://www.cplusplus.com/doc/tutorial/other_data_types/

If you need any clarifications, feel free to ask.
Topic archived. No new replies allowed.