Why does bool and not bool both return true in this case? [duplicate]
The standard (3.9.1/6 Fundamental types) says:
Values of type bool are either true or false.
....
Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false.
Your program's use of memset
leads to undefined behaviour. The consequence of which might be that the value is neither true nor false.
It's not "logically wrong", it's undefined behaviour. bool
is only supposed to contain one of two values, true
or false
. Assigning a value to it will cause a conversion to one of these values. Breaking type-safety by writing an arbitrary byte value on top of its memory (or, as you mention, leaving it unintialised) will not, so you might well end up with a value that's neither true
nor false
.
Internally it is likely using a bitwise not (~
operator) to invert it, which would work when the bool was either zero or all ones:
a = 00000000 (false)
!a = 11111111 (true)
However if you set it to three:
a = 00000011 (true)
!a = 11111100 (also true)