What's the difference between these two enum declarations - C?

馋奶兔 提交于 2019-12-11 05:59:50

问题


I've started learning C and have reached the point of enums. An enum is basically a preferred alternative to DEFINE / const int, correct?

What's the difference between these two declarations?

#include <stdio.h>

// method 1
enum days {
    Monday,
    Tuesday
};

int main()
{
    // method 1
    enum days today;
    enum days tomorrow;

    today    = Monday;
    tomorrow = Tuesday;

    if (today < tomorrow)
        printf("yes\n");

    // method 2
    enum {Monday, Tuesday} days;

    days = Tuesday;
    printf("%d\n", days);

    return 0;
}

回答1:


An enumeration should be preferred over #define/const int when you want to declare variables that can only take on values out of a limited range of related, mutually exclusive values. So the days of the week is a good example, but this would be a bad example:

enum AboutMe
{
    myAge = 27,
    myNumberOfLegs = 2,
    myHouseNumber = 54
};

Going back to your code example; the first method declares a type called enum days. You can use this type to declare as many variables as you like.

The second method declares a single variable of type enum { ... }. You cannot declare any other variables of that type.




回答2:


Being a typenut I would write the first as

typedef enum { Monday, Tuesday } days_t;

and do declaration as

days_t day = Tuesday;

The second method I find no use for.




回答3:


The difference is that in the first case, days is the name of the enumeration. Therefore you can access the definition by

enum days today;

enum days = makes clear which enumeration, the one which is named days

today = variable name

In the second case, days is a variable of the unnamed enumeration.

enum {Monday, Tuesday} days;

enum {Monday, Tuesday} = unnamed enumeration, therefore needs to be defined with the curl brackets {}

days = variable name



来源:https://stackoverflow.com/questions/5038954/whats-the-difference-between-these-two-enum-declarations-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!