Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an enum be reduced to its bit size in C++?

Tags:

c++

Given the following - can I get sizeof(A) to be 1? Right now I'm getting 8, but I'd like A to be equal in layout to Z - as the enum only has one bit of data.

enum BOOL { x , y};

struct A {
    BOOL b : 1;
    unsigned char c : 7;
};
struct Z {
    unsigned char r : 1;
    unsigned char c : 7;
};

int main()
{

    A b;
    b.b = x;
    std::cout << b.b  << "," << sizeof(A) << ","<< sizeof(Z) << std::endl;
    return 0;
}
like image 211
Carbon Avatar asked Jan 25 '26 15:01

Carbon


1 Answers

The issue here is that BOOL will use an int as the underlying type by default. Since it uses an int, it is padding the struct out to have a size of 8 as that will keep the int part of the struct nicely aligned.

What you can do though is specify that you don't want an int, but instead want an unsigned char so that it can pack both bitfields in a single member. This isn't guaranteed, but makes it much more likely to happen. Using

enum BOOL : unsigned char { x , y};

makes A have a sizeof 1 in GCC, Clang and MSVC

like image 194
NathanOliver Avatar answered Jan 28 '26 03:01

NathanOliver



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!