工程布尔比较等于 true 和 false,为什么?
下面的示例编译,但输出相当奇怪:
#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 ) << std::endl;
std::cout << std::boolalpha << ( false == v.c ) << std::endl;
}
输出是:
true
true
有人可以解释为什么吗?
如果重要的话,我正在使用 g++ 4.3.0
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 ) << 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
覆盖
v
使用的内存位置的结果是未定义行为。根据标准,一切都可能发生(包括你的电脑飞走和吃早餐)。
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.
我想我找到了答案。 3.9.1-6 说:
注释 42 说:
I thing I found the answer. 3.9.1-6 says :
Where the note 42 says :
我似乎在标准中找不到任何内容来表明为什么会发生这种情况(很可能是我的错)——这确实包括 7vies 提供的参考,但它本身并没有多大帮助。这绝对是未定义的行为,但我无法解释 OP 观察到的具体行为。
作为一个实际问题,我非常惊讶输出是
使用 VS2010,输出更容易解释:
在后一种情况下,发生的情况是:
true
的比较由编译器测试是否与0x01
相等,并且由于0xff != 0x01
结果为false
。false
的比较也是如此,只是比较的值现在是0x00
。我想不出任何实现细节会导致
false
在解释为bool
时与值0xff
进行比较。有人对此有什么想法吗?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
Using VS2010, the output is the much more easy to explain:
In this latter case, what happens is:
true
are implemented by the compiler as tests for equality to0x01
, and since0xff != 0x01
the result isfalse
.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 value0xff
when interpreted asbool
. Anyone have any ideas about that?在 C++ 标准第 3.9.1 节“基本类型”中找到了这一点(注意神奇的脚注 42):
这对我来说并不完全清楚,但似乎回答了这个问题。
Found this in the C++ standard, section 3.9.1 "Fundamental types" (note the magic footnote 42):
This is not perfectly clear for me, but seems to answer the question.