Printing an uninitialized bool using cout (C++)
Asked Answered
P

3

5

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?

Prostyle answered 28/1, 2010 at 11:37 Comment(0)
T
10

Is this behavior compliant with the standard?

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

Tireless answered 28/1, 2010 at 11:40 Comment(0)
W
4

Yes. An uninitialized variable can have any value.

Wildlife answered 28/1, 2010 at 11:40 Comment(3)
It is difficult to talk about values in the presence of undefined behavior. bool only has two possible values, false and true. The fact that cout << b outputs something other than 0 and 1 is a consequence of the behavior not being defined, not of b having a "value" other than false or true.Yawl
True. It could also print nothing at all, 0.5, "blue", or emit smokePyonephritis
You could turn into a cat. Demons could fly out of your nose.Haymo
D
0

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.

Drice answered 28/1, 2010 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.