Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does c++ merge bitfields?

Tags:

c++

bit-fields

just out of curiosity, if I have a struct with bit fields

struct Foo
{
    char a : 1;
    char b : 1;
    char c : 1;
}

and another struct with bitfields and struct Foo

struct Bar
{
    Foo foo;

    char a : 1;
    char b : 1;
    char c : 1;
}

will all of these bits get packed into a single integer?

How about this case, will these fields get re-ordered to make a single bit field?

struct Baz
{
    char a : 1;

    int NotBitfield;

    char b : 1;
    char c : 1;
}
like image 887
M.kazem Akhgary Avatar asked May 31 '26 10:05

M.kazem Akhgary


1 Answers

I'm not sure about the standard, but as this isn't a language-lawyer question, in gcc and clang sizeof(Bar) gave me two bytes - if they were packed together it'd be only one.

demo

It's possible that somewhere in the standard implies Bar must be at least two bytes; but from the above example we can certainly say that Bar is not guaranteed to be tightly packed (one byte) - at least in practice.


phuclv answered your second question in the comments by providing a link:

Section 9.2.12:

"Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)"

So the compiler can't rearrange the data in Baz.

jaif's answer uses a nice example to illustrate the meaning of the standard here.

like image 74
Elliott Avatar answered Jun 02 '26 01:06

Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!