Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an uninitialized bool using cout (C++)

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?

like image 895
Ari Avatar asked Jan 28 '10 11:01

Ari


2 Answers

Is this behavior compliant with the standard?

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

like image 137
Prasoon Saurav Avatar answered Sep 29 '22 18:09

Prasoon Saurav


Yes. An uninitialized variable can have any value.

like image 24
kennytm Avatar answered Sep 29 '22 19:09

kennytm