user7748100
user7748100

Reputation:

Difference between the following declarations?

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

Answers (2)

BlameTheBits
BlameTheBits

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 enums after not just ints (or longs 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 enums 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 enums - if used reasonable - improves code readability.

Upvotes: 2

  • I think enum seems a little more type-safety. You can do int yourcolors=red, but not colors mycolors=1.
  • When I'm debugging enum usage is helpful. It shows enumeration name instead of its value.
  • Enumeration values aren’t lvalues. So, when you pass them by reference, no static memory is used. It’s almost exactly as if you passed the computed value as a literal.

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

Related Questions