Different types for bit fields of zero length in c?

Fount this statement A zero-width bit field may align the next field at the next container boundary, where the container is the same size as the base type of the bit field

Suppose int is 2 bytes (16 bits) and short is 1 byte (8 bits) to save input. Also suppose we use the gcc compiler (it would be nice to explain the differences in clang).

struct foo { unsigned int a:5; unsigned int :0; unsigned int b:3; } 

In memory, it looks like

 struct address | | v aaaaa000 00000000 bbb00000 00000000 

Question 1: In my opinion, it cannot look like aaaaa000 00000000 0..00bbb00000... , so bbb should align with the container immediately after the current container. Is this really so?

Moving if i point

 struct bar { unsigned short x:5; unsigned int :0; unsigned short y:7; } 

Would that be so?

 struct address | short stops here short starts | | | vv | this is uint | v xxxxx000 00000000 00000000 yyyyyyy0 

Edit 1 It was pointed out that the short cannot be less than 16 bytes. This is a little alongside the question in this matter. But if this is important to you, you can replace short with char and int with short

+6
source share
2 answers

Update by reading the text in context :

The result of your example (fixed using char ):

 struct bar { unsigned char x:5; unsigned int :0; unsigned char y:7; } 

will look like this (assuming a 16-bit int ):

  char pad pad int boundary | | | | vvvv xxxxx000 00000000 yyyyyyy0 

(I ignore endian).

The zero-length bit field causes the position to move to the next int boundary. You defined int as 16-bit, so 16 minus 5 gives 11 bits of indentation.

It does not insert the entire space int . The example on the page you link to demonstrates this (but using 32-bit integers).

+1
source

Firstly, whenever you write bit fields, it is always recommended to declare variables in both ascending and descending sizes of the data types used. Thus, the compiler always selects the highest size of the data type and makes chunks of the same size.

This is what I think.

 struct address | short stops here short starts | | | vv| this is unit | v xxxxx000 00000000 00000000 yyyyyyy0 
-1
source

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


All Articles