Printing an uninitialized bool using cout (C++)

为君一笑 提交于 2019-12-08 16:52:08

问题


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?


回答1:


Is this behavior compliant with the standard?

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




回答2:


Yes. An uninitialized variable can have any value.




回答3:


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.



来源:https://stackoverflow.com/questions/2154132/printing-an-uninitialized-bool-using-cout-c

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