Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit field declaration in a c++ struct

I was reading over the ISO standard of c++ and I came over this bit-field declarations. The following code is not well clear to me

struct {
 char a;
 int b:5,
 c:11,
 :0,
 d:8;
 struct {int ee:8;}
 e;
 } 

Here it is specified that the fields a, d and e.ee have different memory locations and they can be modified independently using multiple threads. The bitfields b and c uses same memory locations so they cant be modified concurrently. I dont understand the significance of using two bit fields for c i.e, c:11,:0,. can anybody clear my vision about this? thank you

like image 992
Tamil Maran Avatar asked Dec 20 '14 05:12

Tamil Maran


2 Answers

You asked;

I dont understand the significance of using two bit fields for c i.e, c:11,:0,. can anybody clear my vision about this?

c is not defined using two bit-fields. The second one is an unnamed bit-field. Unnamed bit-fields with width of zero have special significance. This is what the standard says about unnamed bit-field.

A declaration for a bit-field that omits the identifier declares an unnamed bit-field. Unnamed bit-fields are not members and cannot be initialized. [ Note: An unnamed bit-field is useful for padding to conform to externally-imposed layouts. — end note ] As a special case, an unnamed bit-field with a width of zero specifies alignment of the next bit-field at an allocation unit boundary. Only when declaring an unnamed bit-field may the value of the constant-expression be equal to zero.

like image 75
R Sahu Avatar answered Nov 02 '22 20:11

R Sahu


the :0 listed after c forces d to be aligned on the next word boundary.

It depends on how large your word size is. Supposing your word size is 32 bits, a, b, and c will be crammed into the first 24 bits of your first 32 bits, then the :0 will force the next item, d, to be aligned on the next word. And because the next item is not a bit field, but rather a struct made up of a bit field, it will automatically align itself on the next word boundary.

So, a, b, and c will all be on the same word, then d will be on its own word, then finally your struct, e.

like image 22
Coding Orange Avatar answered Nov 02 '22 20:11

Coding Orange