简体   繁体   中英

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!

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.

  • 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM