在位域中使用枚举是否安全? [英] Is it safe to use an enum in a bit field?
问题描述
说,我有以下结构:
typedef struct my_struct{
unsigned long a;
unsigned long b;
char* c;
unsigned int d1 :1;
unsigned int d2 :4;
unsigned int d3 :4;
unsigned int d4 :23;
} my_type, *p_type;
字段 d3
当前由 #define
的范围从 0x00
到 0x0D
。
The field d3
is currently defined by #define
s that reach from 0x00
until 0x0D
.
实际上, d3
是一个枚举。因此,尝试替换
Actually, d3
is an enumeration. So it's tempting to go ahead and replace
unsigned int d3 :4;
by
my_enum d3 :4;
这是否安全/允许?
代码必须使用各种
- 编译器(GCC,Visual Studio,嵌入式工具)
- 平台(Win32,Linux,嵌入式程序)
- 配置(编译为C,编译为C ++)
很明显,我可以保留 d3
的定义,并在代码中使用枚举,将其分配给 d3
,依此类推,但不适用于C ++。
Obviously, I could leave the definition of d3
as it is and use the enum in my code, assign it to d3
and so on but that's not going to work with C++.
推荐答案
对于C和C ++,答案将有所不同。
Answer will be different for C and C++, this is one for C.
在C中,位域仅限于 signed int
, unsigned int
, _Bool
和 int
在本文中可以是前两个。编译器实现者可以根据自己的喜好添加到该列表中,但需要记录其支持的类型。
In C bitfields are restricted to signed int
, unsigned int
, _Bool
and int
which in this context can be any of the first two. Compiler implementors can add to that list to their liking but are required to document the types that they support.
因此,如果您想绝对确定要回答的问题,请回答您的问题。您的代码可以移植到所有C编译器,不,不能使用 enum
类型。
So to answer your question, if you want to be absolutely sure that your code is portable to all C compilers, no, using an enum
type is not an option.
当前标准中的段内容为:
The corresponding paragraph from the current standard reads:
位字段的类型应为_Bool的合格或不合格
版本,signed
int,unsigned int或其他一些实现定义的类型。由
实现定义是否允许原子类型。
A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
这篇关于在位域中使用枚举是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!