C++ bitfield packing with bools

前端 未结 6 1301
北恋
北恋 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条回答
  •  臣服心动
    2020-12-05 05:18

    Wow, that's surprising. In GCC 4.2.4, the results are 1, 4, and 4, respectively, both in C and C++ modes. Here's the test program I used that works in both C99 and C++.

    #ifndef __cplusplus
    #include 
    #endif
    #include 
    
    struct test1 {
        bool test_a:1;
        bool test_b:1;
        bool test_c:1;
        bool test_d:1;
        bool test_e:1;
        bool test_f:1;
        bool test_g:1;
        bool test_h:1;
    };
    
    struct test2 {
        int test_a:1;
        int test_b:1;
        int test_c:1;
        int test_d:1;
        int test_e:1;
        int test_f:1;
        int test_g:1;
        int test_h:1;
    };
    
    struct test3 {
        int test_a:1;
        bool test_b:1;
        int test_c:1;
        bool test_d:1;
        int test_e:1;
        bool test_f:1;
        int test_g:1;
        bool test_h:1;
    };
    
    int
    main()
    {
        printf("%zu %zu %zu\n", sizeof (struct test1), sizeof (struct test2),
                                sizeof (struct test3));
        return 0;
    }
    

提交回复
热议问题