加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么直接比较两个枚举时会收到错误?

发布时间:2020-12-16 03:35:06 所属栏目:百科 来源:网络整理
导读:我有一些代码移植到一个新的平台,它开始给我一个错误,比较来自两个不同的枚举器列表的两个枚举器.我很困惑为什么它给我一个关于这个错误. C规范(6.7.2.2)的枚举特定部分规定: The identifiers in an enumerator list are declared as constants that have t
我有一些代码移植到一个新的平台,它开始给我一个错误,比较来自两个不同的枚举器列表的两个枚举器.我很困惑为什么它给我一个关于这个错误.

C规范(6.7.2.2)的枚举特定部分规定:

The identifiers in an enumerator list are declared as constants that have type int and
may appear wherever such are permitted.127) An enumerator with = defines its
enumeration constant as the value of the constant expression. If the first enumerator has
no =,the value of its enumeration constant is 0.

所以我应该能够使用与int常量相同的枚举成员.在这个小样本程序中:

enum first {
  a,b
};

enum second {
 c,d
};

int main(){
    enum first myf = a;
    enum second mys = c;

    if(myf == mys)
        printf("same valuen"); 
    return 0;
}

当编译gcc -Wall -Werror时,我收到消息:

error: comparison between ‘enum first’ and ‘enum second’ [-Werror=enum-compare]

我知道,如果我将myf和mysql的类型转换为int,那么编译器将会很开心,就像我可以用myf和mys的值来设置几个int,并进行比较;但为什么我要做这些任何一个来摆脱警告呢?为什么首先存在这个警告?这样做,我看不到会有一些危险.

注意:我已经阅读了关于这个枚举比较标志的gcc文档,但它并没有说什么:

-Wenum-compare
Warn about a comparison between values of different enumerated types. In C++ enumeral mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.

解决方法

这不是一个警告,因为标准合规问题,它是其中之一“这似乎不正确”的警告.如果你想到枚举的典型用法,做这样的比较在许多情况下并没有什么意义.例如:
enum Day {
  Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
};

enum Month {
  January,February,March,April,May,June,July,August,September,October,November,December
};

enum Day day = Wednesday;
enum Month month = April; 

if (day == month) { ... }

这个评估是真实的,但总体上来说,这种比较并没有多大意义.如果你知道你的意思,那么typecast会说服编译器,正如你所说.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读