Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, what does a colon mean inside a declaration? [duplicate]

Possible Duplicate:
What does ‘unsigned temp:3’ means

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

unsigned dumpable:1; 

What does this mean?

like image 866
Tzafrir Avatar asked Jul 06 '10 12:07

Tzafrir


People also ask

What Does a colon mean in C?

It's commonly used to pack lots of values into an integral type. In your particular case, it defining the structure of a 32-bit microcode instruction for a (possibly) hypothetical CPU (if you add up all the bit-field lengths, they sum to 32).

What does colon mean in struct?

Basically, the number after the colon describes how many bits that field uses.


2 Answers

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

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 }; 

then the bits of Foo may be arranged like

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

instead of

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.

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.

like image 193
kennytm Avatar answered Sep 24 '22 18:09

kennytm


It means it's a bitfield - i.e. the size of dumpable is a single bit, and you can only assign 0 or 1 to it. Normally used in old code to save space, or in low-level code that interfaces with hardware (even though the packing is non-portable). See here for more information

like image 36
Airsource Ltd Avatar answered Sep 24 '22 18:09

Airsource Ltd