简体   繁体   中英

how to assign a value to a enum in C?

I have a enum and a struct defined like this:

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:

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 ).

Use the enum symbols verbatim to avoid this warning from 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. Ints are just simple way to tell the different types apart.

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.

使用文本命名而不是Numerics:

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

Your spelling for enum is incorrect in the code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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