本文介绍了在C语言中,声明内的冒号是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习一些内核代码,并遵循以下代码(在linux 2.4中是sched.h,结构是mm_struct):

I'm learning some kernel code, and came along the following line (in linux 2.4, sched.h, struct mm_struct):

unsigned dumpable:1;

这是什么意思?

推荐答案

它是 bitfield 成员.您的代码表示dumpable在结构中恰好占据1位.

It's a bitfield member. Your code means dumpable occupies exactly 1 bit in the structure.

要在位级别打包成员时使用位域.当结构中有很多标志时,这可以大大减少所使用的内存大小.例如,如果我们定义一个具有4个具有已知数字约束的成员的结构

Bitfields are used when you want to pack members in bit-level. This can greatly reduce the size of memory used when there are a lot of flags in the structure. For example, if we define a struct having 4 members with known numeric constraint

0 < a < 20
    b in [0, 1]
0 < c < 8
0 < d < 100

然后可以将该结构声明为

then the struct could be declared as

struct Foo {
   unsigned a : 5;   // 20 < 2^5 = 32
   unsigned b : 1;   //
   unsigned c : 3;   //
   unsigned d : 7;   // 100 < 2^7 = 128
};

然后,Foo 的位可以像

                      ddddddd c  cc b aaaaa
---------  ---------  ---------  ----------
                       octet 1     octet 0
===========================================
                uint32

代替

struct Foo {
   unsigned a;
   unsigned b;
   unsigned c;
   unsigned d;
};

由于值的范围而浪费了很多位

in which many bits are wasted because of the range of values

# wasted space which is not used by the program
# v                                     v
                             ddddddd                                  ccc
------------------------------------ ------------------------------------
            uint32                                 uint32


                                   b                                aaaaa
------------------------------------ ------------------------------------
            uint32                                 uint32

因此您可以通过将多个成员打包在一起来节省空间.

so you can save space by packing many members together.

请注意,C标准没有指定如何在可寻址存储单元"中排列或打包位域.而且,与直接成员访问相比,位域的速度更慢.

Note that the C standard doesn't specify how the bitfields are arranged or packed within an "addressable storage unit". Also, bitfields are slower compared with direct member access.

这篇关于在C语言中,声明内的冒号是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 16:57