Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the size of structures with bit-fields are calculated which contains some unnamed members and zero sized bit-fields?

How the size of this struct is calculated :

struct B {
    unsigned char c1 : 1;
    unsigned char : 2;
    unsigned char c2 : 2;
    unsigned char : 0;
    unsigned char c3 : 4;
    unsigned char c4 : 1;
};

What does this 0 stands for here?, does that mean that it is occupying 0-bits (i.e. no memory)

Can someone explain this to me that how its size is being calculated?

like image 403
Neeraj-Kumar-Coder Avatar asked Dec 06 '25 11:12

Neeraj-Kumar-Coder


1 Answers

A bit-field of size 0 is used to specify that any following bit-fields are to be placed in a separate byte / unit. So the layout of the struct would probably look like this:

| c1|       |   c2  |           |      c3       | c4|           |
-----------------------------------------------------------------
|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12| 13| 14| 15|
-----------------------------------------------------------------

Without the field of size 0, it would probably look like this:

| c1|       |   c2  |      c3       | c4|                       |
-----------------------------------------------------------------
|  0|  1|  2|  3|  4|  5|  6|  7|  8|  9| 10| 11| 12| 13| 14| 15|
-----------------------------------------------------------------

Note however that the ordering of bit-fields in a struct is implementation defined, so it might not look exactly like this.

like image 58
dbush Avatar answered Dec 09 '25 01:12

dbush