简体   繁体   English

如何为C中的枚举赋值?

[英]how to assign a value to a enum in C?

I have a enum and a struct defined like this: 我有一个enum和一个像这样定义的struct

typedef enum
{
   MONDAY = 1,
   TUESDAY,
   WEDNESDAY
} ThreeDays;

typedef struct
{
   int hello;
   ThreeDays day;
} Weekday;

static Weekday weekday = { 1, 2};

Then I got the following Error in lint: 然后我在lint中得到以下错误:

Error 64: Type mismatch (initialization) (int/enum)

What is the reason of this Error? 这个错误的原因是什么? How can I correct it? 我该如何纠正?

Use your enum for what it was built for: 使用你的枚举为它构建的内容:

static Weekday weekday = {1,TUESDAY};

Lint is complaining because you have an enum, but are neither passing a symbol from the enum, nor a cast of a compatible type (such as (ThreeDays)2 ). Lint抱怨是因为你有一个枚举,但既没有传递枚举的符号,也没有兼容类型的演员(如(ThreeDays)2 )。

Use the enum symbols verbatim to avoid this warning from Lint. 逐字使用枚举符号以避免来自Lint的此警告。

From what I have used enum you dont really want to do what you are trying. 从我使用的枚举开始,你真的不想做你正在尝试的事情。 The whole point of it really is to look at it as a type. 它的全部意义在于将其视为一种类型。 By type i mean a order of some type of values that are just represented with the value of ints. 类型i表示某种类型的值的顺序,这些值仅用int的值表示。 Ints are just simple way to tell the different types apart. Ints只是分辨不同类型的简单方法。

For instance you could use them for the days of the weeks 例如,您可以在几周内使用它们

    Enum{
         monday,tuesday, ....
}

Usually when I use it it is to name the structs I am using in a collections of nodes so I can differentiate between my nodes. 通常当我使用它时,它是命名我在节点集合中使用的结构,所以我可以区分我的节点。

Setting your enum to particular numbers kinda defeats the purpose. 将你的枚举设置为特定的数字有点失败了目的。 For what it seems you want a final variable because you want to refer to it when ever you want. 看起来你想要一个最终变量,因为你想在任何你想要的时候引用它。 So just create a final int to get that value when ever. 因此,只需创建一个final int即可获得该值。

使用文本命名而不是Numerics:

use static Weekday weekday = { Mon , Tue , ... } ;

Your spelling for enum is incorrect in the code. 您在枚举时对枚举的拼写错误。

typedef enum { MONDAY = 1, TUESDAY, WENDESDAY }three; working :) 工作:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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