Engineered bool compares equal to both true and false, why?

后端 未结 5 1178
暖寄归人
暖寄归人 2020-12-10 11:04

The example bellows compiles, but the output is rather strange :

#include 
#include 

struct A
{
    int a;
    char b;
    bo         


        
相关标签:
5条回答
  • 2020-12-10 11:31

    Found this in the C++ standard, section 3.9.1 "Fundamental types" (note the magic footnote 42):

    6. Values of type bool are either true or false. 42)
    

    42) Using a bool value in ways described by this International Standard as ‘‘undefined,’’ such as by examining the value of an uninitialized automatic variable, might cause it to behave as if it is neither true nor false.

    This is not perfectly clear for me, but seems to answer the question.

    0 讨论(0)
  • 2020-12-10 11:38

    The result of overwriting memory location used by v is undefined behaviour. Everything may happen, according to the standard (including your computer flying off and eating your breakfast).

    0 讨论(0)
  • 2020-12-10 11:38

    I can't seem to find anything in the standard that indicates why this would happen (most possibly my fault here) -- this does include the reference provided by 7vies, which is not in itself very helpful. It is definitely undefined behavior, but I can't explain the specific behavior that is observed by the OP.

    As a practical matter, I 'm very surprised that the output is

    true
    true
    

    Using VS2010, the output is the much more easy to explain:

    false
    false
    

    In this latter case, what happens is:

    • comparisons to boolean true are implemented by the compiler as tests for equality to 0x01, and since 0xff != 0x01 the result is false.
    • same goes for comparisons to boolean false, only the value compared with is now 0x00.

    I can't think of any implementation detail that would cause false to compared equal to the value 0xff when interpreted as bool. Anyone have any ideas about that?

    0 讨论(0)
  • 2020-12-10 11:45

    A boolean value whose memory is set to a value that is not one or zero has undefined behaviour.

    0 讨论(0)
  • 2020-12-10 11:45

    I thing I found the answer. 3.9.1-6 says :

    Values of type bool are either true or false.42) [Note: there are no signed, unsigned, short, or long bool types or values. ] As described below, bool values behave as integral types. Values of type bool participate in integral promotions (4.5).

    Where the note 42 says :

    42) Using a bool value in ways described by this International Standard as ‘‘undefined,’’ such as by examining the value of an uninitialized automatic variable, might cause it to behave as if it is neither true nor false.

    0 讨论(0)
提交回复
热议问题