简体   繁体   English

使用cout打印未初始化的bool(C ++)

[英]Printing an uninitialized bool using cout (C++)

I have a class with a bool data member that is not initialized by the constructor. 我有一个类,其中bool数据成员未被构造函数初始化。 If I do 如果我做

cout << x.myBoolDataMember;

where x is an object of this class in which the bool has not been initialized, I sometimes get a random number rather than 0 or 1. (I'm using gcc .) Is this behavior compliant with the Standard ? 其中x是此类的一个对象,其中bool尚未初始化,我有时得到一个随机数而不是0或1.(我正在使用gcc 。)这种行为是否符合Standard

Is this behavior compliant with the standard? 这种行为是否符合标准?

Yes! 是! Using garbage values(uninitialized) in your code invokes Undefined Behavior 在代码中使用垃圾值(未初始化)会调用未定义的行为

Yes. 是。 An uninitialized variable can have any value. 未初始化的变量可以具有任何值。

As soon as "<<" operator does not check the bool, this behavior is correct. 一旦“<<”运算符不检查bool,这种行为是正确的。
The problem here is hidden in the bool itself: program uses more than one bit to store the bool. 这里的问题隐藏在bool本身中:程序使用多个位来存储bool。 This is dependent on implementation. 这取决于实施。 Sometimes only one bit can be used to store the bool. 有时只能使用一位来存储bool。
Sometimes more, and it is such a case. 有时候更多,而且就是这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM