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

后端 未结 5 1191
暖寄归人
暖寄归人 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: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?

提交回复
热议问题