这两个枚举声明有什么区别 - C?
我已经开始学习C并且已经达到了枚举的地步。枚举基本上是 DEFINE
/ const int
的首选替代品,对吗?
这两个声明有什么区别?
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您想要声明只能采用有限范围相关值的变量时,应优先使用枚举而不是
#define
/const int
>,互斥值。因此,一周中的几天是一个好示例,但这将是一个坏示例:回到您的代码示例;第一个方法声明一个名为
enum days
的类型。您可以使用此类型来声明任意数量的变量。第二种方法声明一个
enum { ... }
类型的单个变量。您不能声明该类型的任何其他变量。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: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.作为一个打字狂,我会把第一个写成
并将声明写成
第二个方法,我发现没有用处。
Being a typenut I would write the first as
and do declaration as
The second method I find no use for.
不同之处在于,在第一种情况下,days 是枚举的名称。
因此,您可以通过 enum days = 来访问定义
,明确哪个枚举,即名为 days
Today = 变量名的
枚举在第二种情况下,days 是未命名枚举的变量。
enum {Monday, Tuesday} = 未命名枚举,因此需要用大括号定义 {}
days = 变量名
The difference is that in the first case, days is the name of the enumeration.
Therefore you can access the definition by
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} = unnamed enumeration, therefore needs to be defined with the curl brackets {}
days = variable name