Engineered bool compares equal to both true and false, why?
The example bellows compiles, but the output is rather strange :
#include <iostream>
#include <cstring>
struct A
{
int a;
char b;
bool c;
};
int main()
{
A v;
std::memset( &v, 0xff, sizeof(v) );
std::cout << std::boolalpha << ( true == v.c开发者_JS百科 ) << std::endl;
std::cout << std::boolalpha << ( false == v.c ) << std::endl;
}
the output is :
true
true
Can someone explains why?
If it matters, I am using g++ 4.3.0
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.
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).
A boolean value whose memory is set to a value that is not one or zero has undefined behaviour.
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.
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 to0x01
, and since0xff != 0x01
the result isfalse
. - same goes for comparisons to boolean
false
, only the value compared with is now0x00
.
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?
精彩评论