将整数转换为枚举类型是否正确? [英] is it correct to cast an integer to enumerated type?

查看:285
本文介绍了将整数转换为枚举类型是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的研究尚未(在SOF中)给出答案,但是我敢肯定,一定是在以前有人问过这个问题,是否使用了应用程序。

My research has not yielded an answer for this yet (in SOF), but I am sure it must have been asked somewhere before, appologies if so.

I已经在c ++中创建了枚举类型,然后我从消息头中读取了一个值并将其存储到我的枚举类型的变量中,例如:

I have created an enumerated type in c++ and then I read in a value from a message header and want to store it into a variable of my enum type, example:

// My defined enum type
enum myNumType_t
{
    MY_NUM_UNKNOWN = 0,
    MY_NUM1 = 1,
    MY_NUM2 = 2,
    MY_NUM3 = 3,
    MY_NUM4 = 4,
    MY_NUM5 = 5,
};

// In the code
int main()
{
    myNum_t myNum = MY_NUM_UNKNOWN;
    myNum = getMessageNumType(); // returns an int

    return 0;
}

因此,此代码无法在c ++中编译,因为它无法转换int到myNum_t,足够公平。因此,如果我将其强制转换为 myNum =(myNum_t)getMessageNumType(); ,现在可以编译了。但这做对了吗?如果返回值超出myNum_t的范围,会发生什么?

So, this code does not compile in c++ because it can't convert the int to myNum_t, fair enough. So then if I cast it myNum = (myNum_t) getMessageNumType(); this of course now compiles. But does it do the right thing? What happens if the returned value is out of range of myNum_t? Is there a "best practise" here that I am missing?

推荐答案


这是我所缺少的最佳实践吗?

But does it do the right thing?

假设值对枚举类型有效,是的。

Assuming the value is valid for the enumeration type, yes.


如果返回值超出myNum_t的范围会发生什么?

What happens if the returned value is out of range of myNum_t?

这取决于。

直到(不包括)最接近的2的幂次,您保证得到的就是这个值。然后,您的代码将如何处理取决于您。换句话说,给定您的代码,保证(int)(myNumType_t)7 等于7。这很重要,因为某些人对枚举值使用按位运算,因此如果枚举的 BIT0 = 1,BIT1 = 2,BIT2 = 4 ,则表示 BIT0 | BIT1 | BIT2 可以以相同的枚举类型存储。

Up to (and excluding) the nearest power of two, you're guaranteed to get exactly that value. What your code then does with it is up to you. In other words, given your code, (int)(myNumType_t)7 is guaranteed to be equal to 7. This is important because some people use bitwise operations on enumeration values, so if an enumeration has BIT0 = 1, BIT1 = 2, BIT2 = 4, it is intended that BIT0 | BIT1 | BIT2 can be stored in that same enumeration type.

对于较大的值,可以说使用不多。某些实现会将枚举存储在单个(8位)字节中,因此在那些实现中,(int)(myNumType_t)257 不可能等于257。其他的,也许是。最好事先检查整数值来避免这种情况。

For larger values, not much of use can be said. Some implementations would store your enumeration in a single (8-bit) byte, so on those implementations, (int)(myNumType_t)257 could not possibly be equal to 257. On others, it might be. You're better off avoiding that by checking the integer value beforehand.

这篇关于将整数转换为枚举类型是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆