写代码的时候,enum我们当然时经常使用,但是常常很多人没有注意到类型的问题,enum是个常量类型,不能与其他类型直接作比较或计算。
参考代码如下:
typedef enum{
part1 = 0x00,
part2 = 0x01,
part3 = 0x02,
part4 = 0x03,
}test;
test aaa ;
aaa = 0x00; /*错误,enum常量是part1-part4*/
aaa = (test)0x00; /*enum不能强转*/
uint8 u8_type = aaa; /*类型不一样不能赋值*/
fun1(aaa); /*类型不一样不能赋值*/
(extern int fun1(uint8 x);)
fun2(u8_type);
(extern int fun2(test x);)
如果我们要将enum类型赋值给uint8这样,我们可以通过强制转换
uint8 u8_type = (uint8)aaa;
fun1((uint8)a);
那遇到我们需要将uint8类型或者常量赋值给enum的参数怎么办?有三个解决办法。
①编写一个函数(switch)
②使用一个宏定义
③编写一个函数(for)
①编写一个函数(switch)
test enum_switch(uint8 x){
switch(x){....}
}
②使用一个宏定义
#define enum_define(x) (((x) == 0x00) ? part1:())
③编写一个函数(for)
test enum_switch(uint8 x){
for(test = part1;test<=part4;test++)
{
if(x == (uint8)test)
{return test;}
}
}
第三种方法会在test++报错,但是可以运行,具体就是enum不被允许++,这可能就和一些编译器一样会支持enum直接做运算(相当于帮你转换了)。
最后,这些方法同样可以用在:
test aaa &= bbb;(test bbb)
想上面的演示一样,enum不被允许做逻辑预算,这个时候我们依然可以用上面三种方法。
test enum_switch(test x ,test y){
uint8 a;
a = (uint8)x;
a &= (uint8)y;
switch(a){....}
}

459

被折叠的 条评论
为什么被折叠?



