将布尔值更改为 0 或 1 以外的值? [英] Changing a bool to a value other than 0 or 1?
问题描述
我有以下代码:
#include <stdio.h>
int main()
{
bool b;
// Set b to 123
char *p = (char*)&b;
*p = 123;
// Check if b is considered to be true
if (b == true) printf("b is true");
return 0;
}
b
不被认为是 true
,那么 true
究竟是什么意思,是 true
等于1
?
b
is not considered to be true
, so what does true
means exactly, is true
equals to 1
?
忘记说我使用的是 Visual C++.
Forgot to say that I'm using Visual C++.
推荐答案
bool b;
// Set b to 123
char *p = (char*)&b;
*p = 123;
C++ 标准未指定 bool
的存储方式...例如一个编译器使用一个字节而另一个编译器使用四个字节是完全合法的.此外,一个编译器可能存储 0
表示 false
和 all-bits-on 表示 true
和另一个 0
和1
或任何其他值.重要的是,当在布尔上下文中使用时,逻辑可以正常工作,并且在转换为 int
或从 int
转换时:
The C++ Standard leaves it unspecified how bool
are stored... e.g. entirely legal for one compiler to use one byte and another to use four. Further, one compiler might store say 0
for false
and all-bits-on for true
and another 0
and 1
or whatever other values. All that mattered is that when used in a boolean context the logic works correctly, and that when converted to or from an int
:
int(b)
是1
如果b
是true
,并且0
如果b
是false
,并且
int(b)
is1
ifb
istrue
, and0
ifb
isfalse
, and
bool(n)
is true
if-and-only-if n
is not 0
>.
bool(n)
is true
if-and-only-if n
was not 0
.
因此,在测试布尔值时可能会或可能不会咨询 bool
表示中最低内存地址处的字符:它可能是一个编译器生成的代码使用了四个-然后读取的字节 int
仅测试最低有效位或字节,根据字节顺序,*p = 123
可能未触及该字节.类似地,编译器可能会将该值读入一个有符号整数寄存器并测试是否为负(当 true
时期望一个全位值),即使 *p = 123 也可能失败
已写入唯一或最高有效字节.
Because of this, the character at the lowest memory address in the bool
representation may or may not be consulted when testing the value of the boolean: it could be one compiler's generated code uses a four-byte int
that is read then has only the least significant bit or byte tested, which - depending on endianness - may not have been touched by the *p = 123
. Similarly, the compiler might read the value into a signed integer register and test for negativeness (expecting an all-bits-on value when true
), which could also fail even if *p = 123
had written to the only or most significant byte.
因此 - 即使没有其他东西在起作用 - 下面的行可能不会报告b 为真"...
Consequently - even if there was nothing else at play - the line below might not report "b is true"...
// Check if b is considered to be true
if (b == true) printf("b is true");
...但该测试进一步存在缺陷...
...but that test is further flawed by...
可能从未初始化的
bool
表示中的其他字节读取(未初始化的内存读取具有未定义的行为)
possibly reading from other bytes in the
bool
representation that haven't been initialised (uninitialised memory reads have undefined behaviour)
单独使用 bool
值本身就具有未定义行为";就对 bool
内存的二进制写入"而言,只有来自另一个正确初始化的 bool
的完整字节对字节副本才能保证保留此 bool
是可用状态.
fiddling with the bool
value alone inherently has "undefined behaviour"; in terms of "binary writing" to the bool
's memory, only a full byte-for-byte copy from another properly initialised bool
is guaranteed to leave this bool
is a usable state.
这篇关于将布尔值更改为 0 或 1 以外的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!