View Single Post
  #2 (permalink)  
Old 08-06-2007, 06:45 AM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 113
iTrader: (0)
Bench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished roadBench is on a distinguished road
it depends entirely on what you're doing. enum can be used to create a new type, but another useful feature is that an enum constant can convert implicitly to an int. enum can be useful for different things under different circumstances,

Sometimes your data is best represented as a certain type (such as a string), but an operation involving that data is best suited to an integral type.
You could just go for straight integer representation and add a comment in your code, along the lines of
Code:
/*
    Continue = 0
    Won = 1
    Lost = 2
*/
But that wouldn't be very readable ("magic numbers" in code is generally a bad thing), and you could lose track, or find that the numbers needed to change at some point.

Another useful feature of enum's is that they naturally begin at zero (although you can set them to whatever you like), which is a natural match to the way arrays are indexed. Here's a potentially useful example where you can simulate switch'ing with string data.
Code:
#include <string>

enum { Continue, Won, Lost, Invalid };


int lookup( std::string str )
{
    const int elems = 3;
    std::string arr[elems] = { "Continue", "Won", "Lost" };
    for( int i(0); i!=elems; ++i )
        if( arr[i]  == str )
            return i;

    return Invalid;
}

int main()
{
    int i = lookup("Won");

    switch( i )
    {
    case Continue:
        //do something for Continue
        break;
    case Won:
        //Do something for Won
        break;
    case Lost:
        //Do something for Lost
        break;
    }
}

__________________

Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by Bench : 08-06-2007 at 06:55 AM.
Reply With Quote
The Following 2 Users Say Thank You to Bench For This Useful Post:
HelloWorld (08-06-2007), TeraTask (08-06-2007)