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

有没有办法在C90标准中使用enum unsigned(符合MISRA-C 2004标准)

发布时间:2020-12-16 10:51:13 所属栏目:百科 来源:网络整理
导读:我正试图找到一种方法来使枚举“无符号”. enum{ x1 = 0,x2,x3};uint8_t = x2; /* --- PC-LINT MISRA-C 2004 will complain about mixing signed and unsigned here */ 当然,我可以添加一个类型转换来摆脱错误,这是耗时且容易出错的. uint8_t = (uint8_t)x2;
我正试图找到一种方法来使枚举“无符号”.

enum{
     x1 = 0,x2,x3
};
uint8_t = x2; /* <--- PC-LINT MISRA-C 2004 will complain about mixing signed and unsigned here */

当然,我可以添加一个类型转换来摆脱错误,这是耗时且容易出错的.

uint8_t = (uint8_t)x2; /* This works,but is a lot of extra work over the course of 1000s of lines of code*/

那么,有没有办法让MISRA-C 2004想要的特定枚举无符号?

解决方法

没有标准的C方式来控制为枚举选择的类型.您有时可以以特定于实现的方式执行此操作,例如通过向枚举添加一个强制类型为unsigned的值:

enum {
  x1,x3,giant_one_for_forcing_unsigned = 0x80000000;
};

但是,这甚至都不是标准C(因为提供的值不适合int).不幸的是,你几乎没有运气.这是标准中的相关位:

6.7.2.2 Enumeration specifiers,paragraph 4

Each enumerated type shall be compatible with char,a signed integer type,or an unsigned integer type. The choice of type is implementation-defined,but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations,and complete thereafter.

你可能最好使用#define而不是enum来制作你的常量:

#define x1 0U
#define x2 1U
#define x3 2U

uint8_t x = x2;

(编辑:李大同)

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

    推荐文章
      热点阅读