Why does bool and not bool both return true in this case?
boolean, c++
Solution
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.
Problem
This is my code: ``` #include <cstring> #include <iostream> int main() { bool a; memset(&a, 0x03, sizeof(bool)); if (a) { std::cout << "a is true!" << std::endl; } if (!a) { std::cout << "!a is true!" << std::endl; } } ``` It outputs: ``` a is true! !a is true! ``` It seems that the `!` operator on `bool` only inverts the last bit, but every value that does not equal `0` is treated as `true`. This leads to the shown behavior, which is logically wrong. Is that a fault in the implementation, or does the specification allow this? Note that the `memset` can be omitted, and the behavior would probably be the same because `a` contains memory garbage. I'm on gcc 4.4.5, other compilers might do it differently.