The ProgrammersTalk Community
Forum Register Search Today's Posts Mark Forums Read
Register

Go Back   The ProgrammersTalk Community > General Programming > C / C++


Welcome to the The ProgrammersTalk Community forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact contact us.
Tags: ,

Reply
 
LinkBack Thread Tools    Display Modes   
  #1 (permalink)  
Old 08-05-2007, 11:28 PM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,111
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
Icon9 What is ENUM for?

Code:
enum Status { CONTINUE, WON, LOST };
Seems useless to me, why can't you just use string instead?

__________________
PHP Code:
System.out.println("Hello World!"); 

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!
Reply With Quote
  #2 (permalink)  
Old 08-06-2007, 05:45 AM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 112
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 05: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)
  #3 (permalink)  
Old 08-07-2007, 10:18 PM
Forrest
Posts: n/a
Quote:
Originally Posted by HelloWorld View Post
Code:
enum Status { CONTINUE, WON, LOST };
Seems useless to me, why can't you just use string instead?

Well, you can, but in a big project, you have to worry about a typo every now and then, and about case sensitivity. When you use an enum instead, it comes up in IntelliSense ( and you can add XML documentation that will be shown here ) so you can be sure you get it right every time. The refactoring engine makes it easy to change one of the status codes at any time, without getting false positives in a search and replace, but that's a side issue.

I prefer structs that give an int value in plenty of situations, mainly so you don't have to cast to int all the time.

__________________

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!
Reply With Quote
  #4 (permalink)  
Old 08-07-2007, 10:24 PM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,111
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
Quote:
Well, you can, but in a big project, you have to worry about a typo every now and then, and about case sensitivity. When you use an enum instead, it comes up in IntelliSense ( and you can add XML documentation that will be shown here ) so you can be sure you get it right every time.
Hmm.. I never knew this actually happened when we use ENUM instead of the regular string It's cool, but I think it's kind of weird for some reason to have a variable that's not case sensitive, moreover, it's emphasize more to bad coding practice...

__________________
PHP Code:
System.out.println("Hello World!"); 

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!
Reply With Quote
  #5 (permalink)  
Old 08-08-2007, 05:31 AM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 112
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
Enums are case sensitive just like everything else, so I'm not quite sure what Forrest meant by this :-)

__________________

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!
Reply With Quote
The Following User Says Thank You to Bench For This Useful Post:
HelloWorld (08-09-2007)
  #6 (permalink)  
Old 08-13-2007, 04:38 AM
Opiate
Posts: n/a
Quote:
Originally Posted by Bench View Post
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;
    }
}
You didn't name the enum, you passed an Int to that function, and returned a variable that doesn't exist. Did you mean to do that? I am missing anything?

__________________

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!
Reply With Quote
  #7 (permalink)  
Old 08-13-2007, 05:56 AM
Bench Bench is offline
Full Programmer
Join Date: Jul 2007
Location: UK
Posts: 112
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
Quote:
Originally Posted by Opiate View Post
You didn't name the enum, you passed an Int to that function, and returned a variable that doesn't exist. Did you mean to do that? I am missing anything?
I believe you are missing something :-) Everything I did in the program was intentional (And compiled & tested), although I guess there's something which I've left unclear, so i'll try to break it down.

enum's only need to have a name when defining a new type. in this situation, I'm not bothered about creating a type, just the constants which are created between the brackets

What i'm doing is sometimes known as "The enum hack" (Its not really a hack, just a subtle way of using enum) - a way of creating a set of constant identifiers with integral values. Whilst there are other perfectly valid ways of doing this, such as const int and #define, The enum is perfect, because it automatically gives me an ordered, enumerated set of integral constants. (Which are implicitly numbered according to the rules of enum)

So the constants available to the program are
Code:
  Continue = 0,
  Won = 1,
  Lost = 2,
  Invalid = 3
As for the function, lookup(), Here's where the legwork is done. it accepts a std::string (In the body of main() i give it a string, "Won" ), and returns an int. For this function, the constants aren't so important - its concerned with the index of the string in the array, if the string is valid.

If the string is not valid, the 'Invalid' constant is returned (The search doesn't come up with anything). I could have changed it to return 3, or -1, or, or 9999, or something else, but 'Invalid' documents my intentions better than a "magic" number, and, provided the enum block is maintained properly, will not clash with other constants if/when the list is modified.

Once the function returns back to main, the string is out of the picture, now represented by an integral value which can be used inside the switch statement. The switch block is where the enum constants come in handy - They give a clear indication of exactly which string is associated with which 'case' block.
We already know that the function only returns Invalid when the string doesn't match (This can be catered for by the default case), so the cases we need to cater for are the remaining constants. In each case, its pretty obvious which constant matches with which string.


Caveat : the enum and the string array in lookup() need to be maintained together. This unfortunate dependency is one reason why this technique doesn't scale very well. It would be good practice to add an assertion in here somewhere, to make sure that at least the number of elements in the array is always the same as the last enum constant.


As for the £1000 question - why go to all this trouble? why not just scrap the enum and use "magic" numbers? Afterall, the program will work the same, since identifiers such as those used in the enum are all lost once the program compiles. The answer is that the enums and lookup function, if properly maintained, can be reused all over the program, and your code will be more readable than if you'd just gone with some integer literals.

- Of course, - If all you're doing is mapping some strings to a switch block, then you may aswell save yourself the hassle and go for some else/if's. But if your constants are relevent to other parts of the program, then you can shift that dependency to one small block of code.



Edit - Note - I think it would be fair to comment that enums aren't as useful in C++ as in C. table-driven code is often done using the STL 'map' container in C++, and various OO design patterns can be used to reduce dependencies such as the one shown here. However, there are often cases when a few constant integral values fit the bill, and the 'enum hack' ends up being the simplest way to tackle a problem.

__________________

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-13-2007 at 06:19 AM.
Reply With Quote
The Following User Says Thank You to Bench For This Useful Post:
HelloWorld (08-13-2007)
  #8 (permalink)  
Old 08-14-2007, 09:56 PM
ccoonen ccoonen is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jun 2007
Location: Wisconsin
Posts: 308
iTrader: (0)
ccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished road
Enum is an "Enumerated" Variable type - but don't be trapped into assigning numeric values to your Enum Values... It'll only hurt you in the end!
Reply With Quote
  #9 (permalink)  
Old 08-15-2007, 07:39 AM
HelloWorld's Avatar
HelloWorld HelloWorld is offline
Programming Expert
Awards Showcase
Quality Tutorial 
Total Awards: 1
Join Date: Jun 2007
Location: In front of computer...
Posts: 1,111
iTrader: (0)
HelloWorld will become famous soon enoughHelloWorld will become famous soon enoughHelloWorld will become famous soon enough
Quote:
Originally Posted by ccoonen View Post
Enum is an "Enumerated" Variable type - but don't be trapped into assigning numeric values to your Enum Values... It'll only hurt you in the end!
If you don't assigned a numerical value, then do you have any example for the user or ENUM type of variable? I understand that it means "Enumerated" but I'm still looking the useful of it, most of the textbook (such as Deitel) just use it as above example...

__________________
PHP Code:
System.out.println("Hello World!"); 

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!
Reply With Quote
  #10 (permalink)  
Old 08-15-2007, 12:25 PM
ccoonen ccoonen is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jun 2007
Location: Wisconsin
Posts: 308
iTrader: (0)
ccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished roadccoonen is on a distinguished road
generally you will use Enum in place of "Magic Numbers" or Constants.

For example if you had 3 statuses for a user and had them three statuses in the database like:
ID=>1 & Name=>Admin
ID=>2 & Name=>SuperUser
ID=>3 & Name=>User

You would hit the DB, and get back 1 (which is an admin). Now you would set User.UserType (Usertype is your enum) = Admin (Not 1). Then anywhere in your application you can just do:

If User.UserType = (Then intellisense will popup and tell you your options) - no need to remember what it is and it's reliable because it now knows what it can be and you can just select the options from a list.
Reply With Quote
Reply


Thread Tools
Display Modes

   Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -7. The time now is 12:29 PM. Powered by vBulletin
Copyright © 2000 - 2007, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO © 2007 ProgrammersTalk Sedo - Buy and Sell Domain Names and Websites project info: programmerstalk.net Statistics for project programmerstalk.net etracker® web controlling instead of log file analysis


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50