c - 是否允许在位字段中使用short或任何其他类型代替int

标签 c bit-fields

在大多数示例中我都看到过有关位字段的内容 使用unsigned int

struct example
{
    unsigned int number: 1
}

为什么我们不能使用unsigned Short或其他一些数据类型来代替?

最佳答案

来自cppreference.com :

Bit fields can have only one of four types (possibly const or volatile qualified):

  • unsigned int, for unsigned bit fields (unsigned int b:3; has the range 0..7)
  • signed int, for signed bit fields (signed int b:3; has the range -4..3)
  • int, for bit fields with implementation-defined signedness (Note that this differs from the meaning of the keyword int everywhere else, where it means "signed int"). For example, int b:3; may have the range of values 0..7 or -4..3.
  • _Bool, for single-bit bit fields (bool x:1; has the range 0..1 and implicit conversions to and from it follow the boolean conversion rules.

Additional implementation-defined types may be acceptable.

以类似于(位域之外)unsigned charsigned charchar 的方式来思考这一点会有所帮助>(后者的签名是由实现定义的)。

关于c - 是否允许在位字段中使用short或任何其他类型代替int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51404041/

相关文章:

mysql - 为什么 MySQL 查询不能正确插入 BIT(50) 位域

c - C语言中如何给字符串赋值

c - 为什么这个循环永远持续下去?

c - c 结构中的压缩位字段 - GCC

只清除结构的位域成员?

c++ - gcc 抑制警告 "too small to hold all values of"

c++ - 位域和编译指示

c++ - GCC 4.8 在与 libmagic 链接时失败

c - Linux 串行读取()无关数据

c - AIX 上的函数指针编译错误