I do not understand the description of the bit field from the standard C

"whether a field can overlap a word constraint is defined according to the implementation. Fields do not have to be named, unnamed fields are used to fill in (only a colon and width). Special width 0 can be used to force alignment at the next word boundary."

I can not get these lines. Could you explain?

+3
source share
3 answers

"whether the field can overlap the connection of words is determined by the implementation.

Consider two words of memory, where the word size is 32 bits:

[31] [30] [29] ... [2] [1] [0] | [31] [30] [29] ... [2] [1] [0]

If we had a structure:

struct X
{
    int a : 30;
    int b : 4;
};

b, , , b :

[31] [30] [29] ... [2] [1] [0] | [31] [30] [29] [28] ... [2] [1] [0]
a--------------------a b-----------------b
OR
a--------------------a    GAP    b-----------------b

GAP? , b, - , CPU.

; ( ) .

, :

struct X
{
    int a : 30;
    int   : 2;  // unnamed field
    int b : 4;
};

: " 2 a b - (), , , ". 2 , 30 + 2 == 32 ( )... , , . , - , , , , - , , .

0 .

, , , . , , b , 2- (, 30 , 32), ...

struct X
{
    int a : 30;
    int   : 0;  // unnamed field
    int b : 4;
};

... 2 . , a - 64- , , , .

+6

, " ", . 32 4 .

" ", , "" . , . , , " ", , , CPU 2 .

: 0x10000004, 0x10000008. 4 , 4. 0x10000003.

, , CPU 1 0x10000004, 2 0x10000003, .

, . , , , , , .

+1

. , 32 32- . , bools , .

- : , 3 , 0-7.

The field may be unnamed. You do not need to specify fields unless you intend to use them. This can be used to force the creation of a specific layout.

If you use :0, it automatically aligns to the next word boundary.

In general, you do not need this behavior unless you somehow tune performance.

0
source

Source: https://habr.com/ru/post/1751199/


All Articles