Sign in to follow this  

Quick check on enums with values

Recommended Posts

Hi all,

I've noticed that I was using typedef enum and enum without typedef, mixed together.
​Some research/ reading tought me that there's really no difference when you use a c++ compiler, in either way I can simply declare variables without nothing 'enum' (in C it would be this exact difference I believe).

No my question, so far I've explicitly assigned values to my enums, like this:

enum CR_MOUSE_BUTTON
{
	CR_MOUSE_BUTTON_L			= 0,
	CR_MOUSE_BUTTON_M			= 1,
	CR_MOUSE_BUTTON_R			= 2
};

But from what I understand, is that this results in exactly the same as this:

enum CR_MOUSE_BUTTON
{
	CR_MOUSE_BUTTON_L,
	CR_MOUSE_BUTTON_M,
	CR_MOUSE_BUTTON_R,
};

Because the compiler will automatically assign values, going through a list of possible standard types to use (int's, longs etc.).
​I also believe that this also works:

enum CR_MOUSE_BUTTON
{
	CR_MOUSE_BUTTON_L,
	CR_MOUSE_BUTTON_M	= 10,
	CR_MOUSE_BUTTON_R
};

In this case, L/left would get value 0, and R would get value 11 (++ from the forelast enum with value 10).

I just want to be sure if the assumptions above our correct, so I can continue with this knowledge (and remove unnecessary values assignments, because in my use-cases I think I can easily get away without assigning any values to the enums).

Any input is appreciated, as always.

Share this post


Link to post
Share on other sites
Posted (edited)

http://en.cppreference.com/w/cpp/language/enum

 

Each enumerator is associated with a value of the underlying type. When initializers are provided in the enumerator-list, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one.

enum Foo { a, b, c = 10, d, e = 1, f, g = f + c };
//a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12

 

(Why does this need to be a forum question, outside of "For beginners"? This took me 30 seconds to look up, c'mon, we are not google or a reference guide for you. You could have also tested this yourself with ease inside your IDE/application.)

Edited by Juliean

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this