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

后端 未结 7 504
暗喜
暗喜 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:33

    There is this thing in C++ called vector that attempts to exploit the fact that you can theoretically store 8 bools in one char, but it's widely regarded as a mistake by the C++ standards committee. The book "effective stl" actually says "don't use it". That should give you an idea of how tricky it is.

    BTW: Knuth has a book just dedicated to bitwise operations. Boost also has a library dedicated to handling large numbers of bits in a more memory efficient way.

    0 讨论(0)
  • 2020-11-29 05:38

    In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).

    0 讨论(0)
  • 2020-11-29 05:41

    Because in C++ you can take the address of a boolean and most machines cannot address individual bits.

    0 讨论(0)
  • 2020-11-29 05:51

    Actually, in most implementation that I know of sizeof(bool) == sizeof(int). "int" is intended to be the data size that is most efficient for the CPU to work with. Hence things which do not have a specific size (like "char") are the same size as an int. If you had a large number of them per object, you may want to implement a means of packing them for storage, but during normal calculation, it should be left it's native size.

    0 讨论(0)
  • 2020-11-29 05:54

    It takes the same space, because the smallest amount of space you can write in memory is a single byte. Both values are stored in a byte. Although you theoretically only need 1 bit to signify a boolean value, you still have to have a whole byte to store the value.

    0 讨论(0)
  • 2020-11-29 05:56

    Theoretically you only need a single bit for a bool, but working with less than 1 byte's worth of data is messy. You need more instructions to achieve anything and you don't really benefit.

    If you want to pack multiple booleans into a single byte you can use a bit-field structure.

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