Can a bool variable store more than 0x01?

风格不统一 提交于 2019-12-01 23:41:43

问题


#include <iostream>
#include <bitset>

using namespace std;

int main()
{
    bool a = 0x03;
    bitset<8> x(a);
    cout<<x<<endl;

    a = a>>1;
    bitset<8> y(a);
    cout<<y<<endl; 
}

The result is:

00000001    
00000000

The result is not:

00000011
00000001

If I change the type of a from bool to char, the result will be the second one. It means that I cannot store more than 0x01 in a bool, all right value greater than 0x01 are treat as 0x01.

All compiler has the behavior?


回答1:


§4.12 Boolean conversions [conv.bool]

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.




回答2:


bool a = 0x03; converts 0x03 to a boolean value. Since every numeric value that is not zero will be evaluated to be true, you'll see the first result, regardless of which data you'll assign.




回答3:


The only values you can legitimately store in a bool object are false and true. All conversions from other types to bool yield one of those two values. A bool object is always at least 8 bits in size (unless it's a bit field), but the language deliberately makes it difficult to store any of the other 254 (or more) possible values.

You can play tricks, like using memcpy, or using a union, or using pointer conversions, to store any other value that will fit. But if you do so, it probably makes your program's behavior undefined. What that means is that the compiler is permitted to generate code that assumes the stored value is either false or true (or 0 or 1). Store something else, and your program's behavior is unpredictable.

bool is at least 8 bits because the C++ memory model doesn't deal well with sub-byte objects (other than bit fields). You're not supposed to use those other 7 (or more) bits.

IF you want to store more than 2 values in an object, don't make it a bool.




回答4:


C++11, §3.9.1/6:

Values of type bool are either true or false. [...]




回答5:


A bool can only hold two values: false and true.

When/if used in an integer context, a bool can be converted to an int. In this case, false converts to 0 and true converts to 1.

Regardless of the size of storage used for a bool (e.g., sizeof(bool)==1 and sizeof(bool)==4 are both fairly common) it can still only hold the two values false and true, which always convert to 0 and 1 respectively. No other value is possible.




回答6:


Why would you even think you could? It's like saying int i = "abc";.



来源:https://stackoverflow.com/questions/17334126/can-a-bool-variable-store-more-than-0x01

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!