按位补码运算符对 bool 操作数做了意想不到的事情。下面的程序产生这个输出:
x: 123456fe ~x: 87654301 !x: 556677ff
x: 123456ff ~x: 87654301 !x: 556677fe
对于 X 中的任何字节值,~X 似乎总是用 01 覆盖整个字节。 然而,!X 似乎只补充字节的 LSB...
我想如果将 bool 转换为 int,应用按位补码,然后将结果转换回 bool,这是有道理的。 但是,我不明白为什么一个结果会将 8 位写入内存而另一个结果只写入 1 位。
#include "stdio.h"
typedef union {
bool b;
unsigned int i;
} ib_T;
int main(int argc, char **argv) {
ib_T x, y, z;
x.i = 0x123456fe;
y.i = 0x876543ff;
z.i = 0x55667777;
y.b = ~x.b;
z.b = !x.b;
printf("x: %08x ~x: %08x !x: %08x\n", x.i, y.i, z.i);
x.i = 0x123456ff;
y.b = ~x.b;
z.b = !x.b;
printf("x: %08x ~x: %08x !x: %08x\n", x.i, y.i, z.i);
}
最佳答案
从您之前未分配给的 union 成员中读取是未定义的行为。
In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time.
当类型共享一个公共(public)布局时,此规则有一个异常(exception),这不适用于您的情况。一般来说,如果你赋值给x.i
,那么你只能从x.i
读取;如果您想从x.b
开始阅读,您需要先分配给x.b
。
I guess this makes sense if the bool is being converted to an int, the bitwise complement is applied, and the result is converted back to a bool.
这是 100% 正确的:下面的代码片段
bool b;
b = false;
printf("b: %d\n", b);
b = ~b;
printf("~b: %d\n", b);
b = ~b;
printf("~~b: %d\n", b);
打印
b: 0
~b: 1
~~b: 1
bool
被提升为 int
,波浪号 ~
被应用,然后结果被转换回 bool
使用通常的“零/非零”规则。
关于c++ - ~ 运算符对 bool 的行为很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245597/