Why do bool and not bool both return true in this case?

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 like an operator ! on bool only inverts the last bit, but each value not equal to 0 is considered true . This leads to the behavior shown, which is logically incorrect. Is this a bug in the implementation, or does the specification allow it? Note that memset can be omitted, and the behavior is likely to be the same, since a contains memory garbage.

I'm on gcc 4.4.5, other compilers can do it differently.

+67
c ++ boolean
Apr 24 '14 at 12:03
source share
3 answers

The standard (3.9.1 / 6 Basic types) states:

Values โ€‹โ€‹of type bool are either true or false.

....

Using the bool value in ways described in this International Standard as "undefined", for example, by examining the value of an uninitialized automatic object, can make it behave as if it is neither true nor false.

Using your memset program leads to undefined behavior. The consequence of this may be that the meaning is neither true nor false.

+91
Apr 24 '14 at 12:12
source share

This is not "logically incorrect", this behavior is undefined. bool should contain only one of two values: true or false . Assigning a value to it will result in conversion to one of these values. Breaking the security type by writing an arbitrary byte value on top of its memory (or, as you mentioned, leaving it unintelligible) will not, so you can very well get a value that is not equal to true and false .

+41
Apr 24 '14 at 12:10
source share

Inside, most likely, bitwise ( ~ operator) inversion is used, which will work when the bool is either zero, or all:

  a = 00000000 (false) !a = 11111111 (true) 

However, if you set it to three:

  a = 00000011 (true) !a = 11111100 (also true) 
+3
Apr 26 '14 at 9:31
source share



All Articles