C++ bitfield packing with bools

前端 未结 6 1292
北恋
北恋 2020-12-05 04:19

I\'ve just done a test with bitfields, and the results are surprising me.

class test1 {
public:
    bool test_a:1;
    bool test_b:1;
    bool test_c:1;
            


        
6条回答
  •  -上瘾入骨i
    2020-12-05 05:06

    #include 
    using namespace std;
    
    bool ary_bool4[10];
    
    struct MyStruct {
        bool a1 :1;
        bool a2 :1;
        bool a3 :1;
        bool a4 :1;
        char b1 :2;
        char b2 :2;
        char b3 :2;
        char b4 :6;
        char c1;
    };
    
    int main() {
        cout << "char size:\t" << sizeof(char) << endl;
        cout << "short int size:\t" << sizeof(short int) << endl;
        cout << "default int size:\t" << sizeof(int) << endl;
        cout << "long int size:\t" << sizeof(long int) << endl;
        cout << "long long int size:\t" << sizeof(long long int) << endl;
        cout << "ary_bool4 size:\t" << sizeof(ary_bool4) << endl;
        cout << "MyStruct size:\t" << sizeof(MyStruct) << endl;
        // cout << "long long long int size:\t" << sizeof(long long long int) << endl;
        return 0;
    }
    
    char size: 1
    short int size: 2
    default int size: 4
    long int size: 4
    long long int size: 8
    ary_bool4 size: 10
    MyStruct size: 3
    

提交回复
热议问题