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.