为什么在这种情况下bool和not bool都返回true? [英] Why does bool and not bool both return true in this case?

查看:249
本文介绍了为什么在这种情况下bool和not bool都返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

#include <cstring>
#include <iostream>
int main() {
    bool a;
    memset(&a, 0x03, sizeof(bool));
    if (a) {
        std::cout << "a is true!" << std::endl;
    }
    if (!a) {
        std::cout << "!a is true!" << std::endl;
    }
}

它输出:

a is true!
!a is true!

bool上的!运算符似乎只反转最后一位,但每个不等于0的值都被视为true.这导致显示的行为,这在逻辑上是错误的.这是实现中的错误,还是规范允许这样做?请注意,可以省略memset,并且行为可能相同,因为a包含内存垃圾.

It seems that the ! operator on bool only inverts the last bit, but every value that does not equal 0 is treated as true. This leads to the shown behavior, which is logically wrong. Is that a fault in the implementation, or does the specification allow this? Note that the memset can be omitted, and the behavior would probably be the same because a contains memory garbage.

我使用的是gcc 4.4.5,其他编译器可能会有所不同.

I'm on gcc 4.4.5, other compilers might do it differently.

推荐答案

标准(3.9.1/6基本类型)说:

The standard (3.9.1/6 Fundamental types) says:

布尔类型的值为true或false.

Values of type bool are either true or false.

....

以本国际标准描述为未定义"的方式使用布尔值,例如检查 未初始化的自动对象,可能会导致其行为既不正确也不错误.

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

您的程序对memset的使用会导致未定义的行为.结果可能是该值既不是true也不是false.

Your program's use of memset leads to undefined behaviour. The consequence of which might be that the value is neither true nor false.

这篇关于为什么在这种情况下bool和not bool都返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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