为什么在这种情况下 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
的值都被当作<代码>真代码>.这导致了所示的行为,这在逻辑上是错误的.这是实现中的错误,还是规范允许这样做?请注意,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 Fundamental types)说:
The standard (3.9.1/6 Fundamental types) says:
bool 类型的值为真或假.
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
的使用会导致未定义的行为.其结果可能是该值既不是真也不是假.
Your program's use of memset
leads to undefined behaviour. The consequence of which might be that the value is neither true nor false.
相关文章