Why is a char and a bool the same size in c++?

后端 未结 7 525
暗喜
暗喜 2020-11-29 05:05

I\'m reading The C++ Programming Language. In it Stroustrup states that sizeof(char) == 1 and 1 <= sizeof(bool). The specifics depend

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 05:58

    A byte is the smallest addressable unit of memory.

    Consider the following code:

        bool b[9];
        bool *pb0 = &b[0];
        bool *pb1 = &b[1];
    
        for (int counter=0; counter<9; ++counter)
        {
             // some code here to fill b with values
             b[counter] = true;
    
        }
    

    If bool is stored as 1 bit, then pb0 will equal pb1, because both have the same address. This is clearly not desirable!

    Additionally the assignment in the loop will result in non-trival assembly code. It will involve a different bit shift in each iteration of the loop. In high-performance software, those extra bit-shift operations can slow down the application needlessly.

    The STL library provides a work-around in situations where space DO matter. The use of std::vector will store bool as 1 bit. The paradox of the example above do not apply because

    • the overloading of operator[] hides the rigors of the bit shift operation
    • the use of iterators instead of pointers give additional flexibilty to the implementation

提交回复
热议问题