简体   繁体   English

如何为枚举变量赋予枚举

[英]how to assign enum to enum variable

I have the following code in C: 我在C中有以下代码:

typedef enum
{
   MONDAY = 0,
   TUESDAY,
   WEDNESDAY
} Weekday;

typedef struct
{
   int age;
   int number;
   Weekday weekday;
} Info;

typedef struct
{
   int age;
   Weekday weekday;
} Data;

Info info;
Data data;
info.weekday = data.weekday;

The lint gives the following error: lint给出以下错误:

info.weekday = data.weekday; Type mismatch (assignment) (enum/enum)

how to assign a enum to another enum variable? 如何将枚举分配给另一个枚举变量?

Replace the semicolon with a comma here : 在这里用逗号替换分号:

MONDAY = 0;

If there's still an error, you need to show more code. 如果仍有错误,则需要显示更多代码。

Edit : My fault, didn't know "lint". 编辑:我的错,不知道“lint”。

It seems that lint is a bit too paranoid. 似乎皮棉有点过于偏执。 That kind of assignment could not possibly go wrong. 这种任务不可能出错。 So as AnthonyLambert said, just disable this error (or don't use lint ?). 所以AnthonyLambert说,只是禁用此错误(或不使用lint?)。

One last trick I can think of, but I wouldn't bet on it, is to name your enum : 我能想到的最后一招,但我不打赌,就是命名你的枚举:

typedef enum Weekday
{
    //...
} Weekday;

The last option you have, which I don't recommend either, is to use int in your structures : 您拥有的最后一个选项(我不建议使用)是在结构中使用int:

typedef struct
{
    // ...
    int weekday;
} Info;

Then you can assign enumerators to these variables. 然后,您可以为这些变量分配枚举器。

Your code is not incorrect, it's just lint pointing out a potential error. 你的代码不正确,只是lint指出了潜在的错误。 this error would not show up if compiled with a C++ compiler where it retains the type info. 如果使用C ++编译器编译,它将保留类型信息,则不会显示此错误。

The problem is that in C as soon as you assign a enum value it becomes an int type. 问题是,只要你分配一个枚举值,就会在C中变成一个int类型。 So as soon as you read from Weekday its type is now int not Weekday. 所以,一旦你从工作日读到它的类型现在是int而不是工作日。

The way to get round the error being reported in lint by coding would be to force it to assign from the enum again like so. 通过编码来解决在lint中报告的错误的方法是强制它再次从枚举中分配。

void SetWeekday( Info *info, Data* data )
{
     switch (Data->Weekday)
     {
         case MONDAY: info->Weekday = MONDAY;
         case TUESDAY: info->Weekday = TUESDAY;
         etc...
     }
}

Alternatively lint allows you to disable each error individually, would is probably best. 或者lint允许您单独禁用每个错误,可能是最好的。

( This code has not been compiled and may contain nuts and/or small insects. etc... ) (此代码尚未编译,可能包含坚果和/或小昆虫等。)

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

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