将布尔值更改为 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


编辑: 忘了说我正在使用 Visual C++。

true 表示 1

但是123也被认为是真的(一般都是除零以外的整数)

如果你说

if (b) printf("b is true");

你必须得到输出 b is true

bool b;

// Set b to 123
char *p = (char*)&b;
*p = 123;

C++ 标准未指定 bool 的存储方式...例如一个编译器使用一个字节而另一个编译器使用四个字节是完全合法的。此外,一个编译器可能会为 false 存储 say 0,为 true 和另一个 01 或任何其他值存储所有位。重要的是,当在布尔上下文中使用时,逻辑可以正常工作,并且当转换为 int:

或从 int:

转换时
    如果 btrue
  • int(b)1,如果 b 是 [=14,则 0 =],以及

  • bool(n)true 当且仅当 n 不是 0.

因此,在测试布尔值时可能会或可能不会参考 bool 表示中最低内存地址的字符:它可能是编译器生成的代码使用四字节然后读取的 int 仅测试了最低有效位或字节,这取决于字节序 - 可能未被 *p = 123 触及。类似地,编译器可能会将值读入带符号的整数寄存器并测试是否为负(在 true 时期望全位值),即使 *p = 123 已写入唯一或最高有效字节。

因此 - 即使没有其他事情在起作用 - 下面的行可能不会报告 "b is true"...

// Check if b is considered to be true
if (b == true) printf("b is true");

...但是该测试还存在缺陷...

  • 可能从 bool 表示中尚未初始化的其他字节读取(未初始化的内存读取具有未定义的行为)

  • 单独摆弄 bool 值本身就有 "undefined behaviour";就 "binary writing" 到 bool 的内存而言,只有来自另一个正确初始化的 bool 的完整字节对字节副本才能保证留下这个 bool 是可用的州.

C++11 说 (3.9 "Types" [basic.types]):

The value representation of an object is the set of bits that hold the value of type T. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values

和(3.9.1 "Fundamental types" [basic.fundamental]):

For character types, all bits of the object representation participate in the value representation. For unsigned character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types.

...

Values of type bool are either true or false

最后,5 "Expressions" [expr] 说:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

发生的事情是,当您将值 123 写入 bool 对象占用的内存(通过 char* p)时,您正在写入一些无法表示的内容bool 对象的 'value representation'。因此,当您随后通过左值 b 访问该对象时,程序表现出未定义的行为并且您有一个既不是 true 也不是 false.

bool 对象

并回答您关于 true 的值是什么的问题:该标准从未真正指定。它确实指定 truebool 类型可以表示的两个值之一(当然另一个是 false)。该标准还规定 true 很容易转换为 1,反之亦然,1 很容易转换为 true。这些转换发生得如此自然和容易,以至于我认为几乎每个人都认为 true 的值为 1.

要记住的一件事是,几乎任何非零整数值都会很容易地转换为 true - 而不仅仅是 1。但是在您的示例中对于值 123 不会发生这种情况,因为在该表达式中它正在写入 char 类型的左值,因此不会发生到 bool 的转换。