How a bool type variable is stored in memory? (C++)

后端 未结 3 1996
不知归路
不知归路 2021-01-18 05:44

bool test;

sizeof(test) = 1 if using VS 2010. Since every C++ data type must be addressable, the \"test\" bool variable is 8-bits(1 byte).

My qu

相关标签:
3条回答
  • 2021-01-18 05:53

    Every element of test1 must be addressable. This implies that test1 takes at least 32 bytes (and not bits).

    If you want multiple boolean values to be stored in a single variable, use std::bitset or std::vector<bool> (but be aware that the latter is not really a vector of bools, it is a specialization designed to save space).

    IIRC, C++11 also defines std::dynamic_bitset.

    0 讨论(0)
  • 2021-01-18 06:00

    Another possibility to have a variable of 1 bit, is to put into a bitfield struct:

    struct {
        int a:1;
        int b:1;
    };
    
    0 讨论(0)
  • My question is that does the "test" variable really occupy 1 byte in memory?

    Yes, if sizeof(bool)==1 . Basically, the sizeof bool is implementation-defined, which means it could be greater than 1 byte for certain compiler.

    bool test1[32](in VS 2010), int test2(in VS 2010)
    Does test1 and test2 occupy the same memory?

    What each of them occupy can be known by using sizeof operator. That is what sizeof operator is for. So test1 and test2 will occupy sizeof(test1) and sizeof(test2) bytes respectively.

    0 讨论(0)
提交回复
热议问题