工程bool比较等于true和false,为什么? [英] Engineered bool compares equal to both true and false, why?

查看:251
本文介绍了工程bool比较等于true和false,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例编译,但输出是相当奇怪:

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;
}

输出为:

true
true

为什么?

如果重要,我使用g ++ 4.3.0

If it matters, I am using g++ 4.3.0

推荐答案

在C ++标准,第3.9.1节基本类型(请注意魔法脚注42)中找到:

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)标准为未定义,例如通过检查未初始化的自动变量的值,可能会导致它的行为不是真的也不是假的。

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.

这篇关于工程bool比较等于true和false,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆