问题
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