C/C++: How to convert int to enum?

Started by
15 comments, last by GameDev.net 18 years, 9 months ago
Hi all, Is there a way to convert an int to enum? For example, I declared the following enum type:

enum Days               // Declare enum type Days
{
   saturday,            // saturday = 0 by default
   sunday,          	// sunday = 1
   monday,              // monday = 2
   tuesday,             // tuesday = 3
   wednesday,           // etc.
   thursday,
   friday
}

Days today;

Is there a way to set today to Wednesday using an integer, like this: today = 3 According to C documents, the following is legal, but result is not defined today = (Days)0;
Advertisement
Quote:Original post by faculaganymede
According to C documents, the following is legal, but result is not defined
today = (Days)0;


My C++ compiler has no problem with that (VS 2003). I've seen casting arbitrary integers to enums like that before, I think that's how you're supposed to do it.

EDIT: Is this C or C++? There might be a difference between the two.

EDIT2: Yeah, that's the right way in C++ at least. See these links:

One
Two
To be safe, define the first element zero.

saturday = 0,
...

Kuphryn
You can do that just fine, without casting. Another good practice is to have a last enumeration. For example:

enum Days               // Declare enum type Days{   saturday,            // saturday = 0 by default   sunday,          	// sunday = 1   monday,              // monday = 2   tuesday,             // tuesday = 3   wednesday,           // etc.   thursday,   friday,   LAST_DAY             // used for looping}Days today;


Then you can loop through your enum...

for(int i = 0; i < LAST_DAY; i++)    if(today == wednesday)        std::cout << "Today is Hump-Day!!!";
Thanks everyone for your quick feedbacks.

I am programming in C++ using MS VS 6.0.

Here's MSDN library doc that I was referring to ealier. The very last line seems to say enum typecast is not possible.
---------------------------------------------------------------------------
enum
enum [tag] {enum-list} [declarator]; // for definition of enumerated type

enum tag declarator; // for declaration of variable of type tag

The enum keyword specifies an enumerated type.

An enumerated type is a user-defined type consisting of a set of named constants called enumerators. By default, the first enumerator has a value of 0, and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator. Enumerators needn’t have unique values. The name of each enumerator is treated as a constant and must be unique within the scope where the enum is defined. An enumerator can be promoted to an integer value. However, converting an integer to an enumerator requires an explicit cast, and the results are not defined.

In C, you can use the enum keyword and the tag to declare variables of the enumerated type. In C++, you can use the tag alone.

In C++, enumerators defined within a class are accessible only to member functions of that class unless qualified with the class name (for example, class_name::enumerator). You can use the same syntax for explicit access to the type name (class_name::tag).

For related information, see class and struct.

Example

// Example of the enum keyword
enum Days // Declare enum type Days
{
saturday, // saturday = 0 by default
sunday = 0, // sunday = 0 as well
monday, // monday = 1
tuesday, // tuesday = 2
wednesday, // etc.
thursday,
friday
} today; // Variable today has type Days

int tuesday; // Error, redefinition of tuesday

enum Days yesterday; // Legal in C and C++
Days tomorrow; // Legal in C++ only

yesterday = monday;

int i = tuesday; // Legal; i = 2
yesterday = 0; // Error; no conversion
yesterday = (Days)0; // Legal, but results undefined
Just having done a quick test, in VS.net 2003, this throws up no compiler or runtime errors

enum Days{	Monday,	Tuesday,	Wednesday,	Thursday,	Friday,	Saturday,	Sunday,};int _tmain(){	Days	normalDay, illegalDay;	normalDay = (Days)2;	illegalDay = (Days)234;	return 0;}


I'm assuming that the documentation is refering to the illegalDay line when describing the casting as undefined.

Casting 2 (or any valid number) will give you the corresponding enum. What 234 gives you I dont know.

I really wouldn't worry about this to be honest, as long as you are using valid numbers to cast. And as long as you have the max days enum mentioned in a earlier post, there should be no chance of you making an error (unless you declare the first value >0, in which case you should be careful)

Spree
Keep in mind that your assuming an enum is the size of an int. It doesn't have to be:). YOu can force it to be atleast as large as an in by assigning an enum entry to have a value greater than a short or word.

An enum can be the size of a char or a int16 or an int 32 or an int64.

So casting can be dangerous.

Cheers
CHris
CheersChris
As others have mentioned, doing the cast like that should work everywhere as long as the int is legit.

Personally, I've moved away from enums due to other reasons and &#111;nly really use them now when the result absolutely never, ever needs displayed or inputed by users or between components. Which is rare to say the least.
Quote:Original post by kuphryn
To be safe, define the first element zero.

saturday = 0,
...

Kuphryn


The value of the first enum element is always 0 if it is not initialized (see the C++ standard, section 7.2, § 1).

Regards,

Quote:Is there a way to set today to Wednesday using an integer, like this:
today = 3

According to C documents, the following is legal, but result is not defined
today = (Days)0;


Why not just do this:
today = saturday;


an enumeration is just a list of constants so it would be just the same as doing this:
#define saturday     0int today = saturday;

or
const int saturday = 0;int today = saturday;


Someone please correct me if i'm wrong.
F-R-E-D F-R-E-D-B-U-R...G-E-R! - Yes!

This topic is closed to new replies.

Advertisement