Reputation:
I have theenumerated type, colors:
enum colors {green, red, blue};
Is colors mycolors=red
the same as int yourcolors=red
and is the type of each enumerator int
? The both will have a value of 1, right?
Thanks!
Upvotes: 0
Views: 111
Reputation: 861
I just want to post a little code snippet to prove the comments of Jason Lang and Kerrek SB:
#include <iostream>
#include <typeinfo>
enum colors {green, red, blue};
int main()
{
colors mycolors=red;
int yourcolors=red;
if (mycolors == yourcolors)
std::cout << "same values" << std::endl;
if (typeid(mycolors) != typeid(yourcolors))
std::cout << "not the same types" << std::endl;
return 0;
}
Running this code will lead into the following console output:
same values
not the same types
Also (as Daniel Kamil Kozar mentioned) there is enum class
(only C++11 and later!). See this Question for more information about why to prefer enum class
over enum
.
Regarding the question 'why are enum
s after not just int
s (or long
s or ...) just think of operator overloading. That is ++ colors(green) == 1
must not be true.
Confirm this Question that operator overloading is possible for plain enum
s and this question and the accepted answer to see how to avoid casting in overloading operators of an 'enum class'.
At last keep in mind that the usage of enum
s - if used reasonable - improves code readability.
Upvotes: 2
Reputation: 20931
enum
seems a little more type-safety. You can do int yourcolors=red
, but not colors mycolors=1
.enum KEYS
{
UP,
RIGHT,
DOWN,
LEFT
};
void (KEYS select)
{
switch (select)
{
case UP:
case RIGHT:
case DOWN:
case LEFT: break;
default: exit(1);
}
}
Upvotes: 1