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

C++Boolean

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Solution 3 - C++

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflyxView Question on Stackoverflow
Solution 1 - C++David HeffernanView Answer on Stackoverflow
Solution 2 - C++Mike SeymourView Answer on Stackoverflow
Solution 3 - C++MrZebraView Answer on Stackoverflow