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.
bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?
A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.
True and False are instances of bool and therefore instances of the parent class int , but bool itself is not an instance of int . Being a class it's an instance of type and a subclass of int .
Numbers. In Python, the integer 0 is always False , while every other number, including negative numbers, are True .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With