c++ - 在位字段中使用枚举是否安全?

标签 c++ c enums bit-fields

说,我有以下结构:

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 .

其实,d3是一个枚举。所以很想继续替换

    unsigned int        d3  :4;

通过

    my_enum             d3  :4;

这是安全/允许的吗?

代码必须用各种编译

  • 编译器(GCC、Visual Studio、嵌入式)
  • 平台(Win32、Linux、嵌入式)
  • 配置(编译为 C,编译为 C++)

显然,我可以保留 d3 的定义。照原样并在我的代码中使用枚举,将其分配给 d3等等,但这不适用于 C++。

最佳答案

在所有支持标准的 C++ 编译器中都允许。

C++03 标准 9.6/3

A bit-field shall have integral or enumeration type (3.9.1). It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int or long bit-field is signed or unsigned.

C++03 标准 9.6/4

If the value of an enu- merator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type, the original enumerator value and the value of the bit-field shall compare equal.

例子

enum BOOL { f=0, t=1 };

struct A {
    BOOL b:1;
};

void f() {
    A a;
    a.b = t;
    a.b == t // shall yield true
}

但你不能认为枚举具有无符号基础类型。

C++03 标准 7.2/5

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enu- merator cannot fit in an int or unsigned int

关于c++ - 在位字段中使用枚举是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11983231/

相关文章:

c - C 嵌入式应用程序中 time() 函数的问题

c - 从 UART 接收的数据中获取子字符串并放入 LCD

c++ - 使用 for 循环读取和写入同一个文本文件

c++ - 在子类中覆盖时连接到基类的信号

c++ - 编译器是否优化 C++ 中静态值的 if 语句

C++ 初学者 : function call on object not executing properly

c++ - 如何对一些结构进行选择排序

c# - C# 中枚举的替代方法 - 嵌套

java - 字符串 switch case 标签的编译器错误

c#-4.0 - 有什么替代 C# 4.0 中极其昂贵的 Enum.IsDefined() 的方法?