Printing an uninitialized bool using cout (C++)

2019-06-16 18:02发布

I have a class with a bool data member that is not initialized by the constructor. 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?

3条回答
Evening l夕情丶
2楼-- · 2019-06-16 18:54

Yes. An uninitialized variable can have any value.

查看更多
Ridiculous、
3楼-- · 2019-06-16 19:01

As soon as "<<" operator does not check the bool, this behavior is correct.
The problem here is hidden in the bool itself: program uses more than one bit to store the bool. This is dependent on implementation. Sometimes only one bit can be used to store the bool.
Sometimes more, and it is such a case.

查看更多
Ridiculous、
4楼-- · 2019-06-16 19:04

Is this behavior compliant with the standard?

Yes! Using garbage values(uninitialized) in your code invokes Undefined Behavior

查看更多
登录 后发表回答