Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different types for zero length bit fields in c?

Tags:

c

bit-fields

Fount this statement A zero-width bit field can cause the next field to be aligned on the next container boundary where the container is the same size as the underlying type of the bit field

To put it into practice assuming int is 2 bytes (16 bits) and that short is 1 byte (8 bits) to save typing. Also let's say we are using the gcc compiler (would be nice to explain the differences to clang).

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

In memory this looks like

struct address
   |            
   |
   v
   aaaaa000 00000000 bbb00000 00000000

Question 1: In my understanding it can not look like aaaaa000 00000000 0..00bbb00000..., So bbb has to align with the container directly following the current container. Is this actually true?

Moving on, if I specify

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

Will it be like so?

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

Edit 1 It was pointed out that short can not be less than 16 bytes. That is slightly beside the point in this question. But if its important to you you can replace short with char and int with short

like image 628
user10607 Avatar asked Nov 03 '14 17:11

user10607


1 Answers

Update, after reading the text in context:

The result of your example (corrected to use char):

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

would look like this (assuming 16-bit int):

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

(I'm ignoring endian).

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

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

like image 152
ams Avatar answered Sep 30 '22 15:09

ams