C语言 如何比较枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13304849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:22:52  来源:igfitidea点击:

how to compare enum values

cenums

提问by ouah

I have a question about enumC.

我有一个关于enumC的问题。

I defined an enumin the following way:

enum用以下方式定义了一个:

typedef enum
{
    Hello1 = 1,
    Hello2 = 2,
    Hello3 = 3
}Hello

Hello hello;

int value = 3;  

then how to compare the value with the value in Hello?

那么如何将值与中的值进行比较Hello

for example:

例如:

if(value == Hello3)
{
}

or should I do it like the following:

或者我应该这样做:

if(value == Hello.Hello3)
{
}

回答by ouah

This way is correct:

这种方式是正确的:

 if (value == Hello3)
 {
 }

enumconstants are of type int.

enum常量的类型是int

Your second construct is invalid.

您的第二个构造无效。

回答by Omkant

enumis not a structure and the member names are just names of the corresponding constants. These names defined in enumare not the data members of enumlike in struct(as you are thinking).

enum不是结构,成员名称只是相应constants. 在 inenum中定义的这些名称不是enumlike in的数据成员struct(如您所想)。

So remember enumare used to define a list of named integer constants which we can do using #definealso.

所以请记住enum用于定义我们也可以使用的命名整数常量列表#define

So here in your case:

所以在你的情况下:

if(value == Hello3)
{
}

This is the correct way to compare as it replaces Hello3by the value 3(which is nothing but int) at compile time.

这是正确的比较方法,因为它在编译时替换Hello3为值3(除了int)。

For example you can do it also like this:

例如,您也可以这样做:

Hello hello=2;
if(hello == Hello2)
{
}