Friday, February 10, 2012

enum c++

enum c++:

C++ allows programmers to create their own data types. Perhaps the simplest method for doing so is via an enumerated type. An enumerated type is a data type where every possible value is defined as a symbolic constant (called an enumerator). Enumerated types are declared via the enum keyword. For example

// define a new enum WeekDay
enum WeekDay {
    Monday,     //    assigned 0
    Tuesday,    //    assigned 1
    Wednesday,  //    assigned 2
    Thursday,   //    assigned 3
    Friday,     //    assigned 4
    Saturday,   //    assigned 5
    Sunday      //    assigned 6
};
// declare a variable
WeekDay day = Monday;

Defining an enumerated type does not allocate any memory. When a variable of the enumerated type is declared (such as day in the example above), memory is allocated for that variable at that time.

Enum variables are the same size as an int variable. This is because each enumerator is automatically assigned an integer value based on it’s position in the enumeration list. By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:

enum WeekDay {
    Monday,     //    assigned 0
    Tuesday,    //    assigned 1
    Wednesday,  //    assigned 2
    Thursday,   //    assigned 3
    Friday,     //    assigned 4
    Saturday,   //    assigned 5
    Sunday      //    assigned 6
};
WeekDay day = Monday;
cout << day << endl;

The cout statement above prints the value0.

It is possible to explicitly define the value of enumerator. These integer values can be positive or negative and can be non-unique. Any non-defined enumerators are given a value one greater than the previous enumerator.

enum WeekDay {
    Monday    = -3,
    Tuesday,       //    assigned -2
    Wednesday = 5, //    assigned -1
    Thursday  = 5,
    Friday,        //    assigned 6
    Saturday,      //    assigned 7
    Sunday         //    assigned 8
};

Because enumerated values evaluate to integers, they can be assigned to integer variables:

int nValue = Thursday;

However, the compiler will not implicitly cast an integer to an enumerated value. The following will produce a compiler error:

WeekDay day = 5; // will cause the compiler error

It is possible to use a static_cast to force the compiler to put an integer value into an enumerated type, though it’s generally bad style to do so:

WeekDay day = static_cast <day>5; // no compiler error, bad style

Each enumerated type is considered a distinct type. Consequently, trying to assign enumerators from one enum type to another enum type will cause a compile error:

WeekDay day = SOME_OTHER_ENUM_VALUE; // compiler error
Enumerated types are incredibly useful for code documentation and readability purposes when you need to represent a specific number of states.

Example:

No comments:

Post a Comment