按位排他或 ^ with stdbool.h C 中的 bool 类型和赋值

bitiwise exclusive or ^ with stdbool.h bool types in C and assignment

我有一个玩具程序,我在其中使用 <stdbool.h> 库来使用类型 bool。我有几个 bool 的数组,下面的命令循环工作。

我在网上看到我不应该对布尔值使用按位逻辑。他们似乎在这里工作。这只是我的编译器的运气,还是我只是误解了有关按位运算符的警告?

#include <stdio.h> 
#include <stdbool.h>

#define N 5
int main(void) {
  bool a[N] = { true, true, false, false, false };
  bool b[N] = { true, false, false, true, false };

  /* to count how many pairs are opposite */
  int count = 0;
  for (int i = 0; i < N; ++i){ count += (a[i] ^ b[i]); } 
  printf(" # pairs opposite: %i\n", count);

  /* flip the values of a */
  for (int i = 0; i < N; ++i){ 
        a[i] = (a[i] ^ true);
        printf(" %i", a[i]);
  } 
  printf("\n");

  /* flip only the value of a that are true in b */
  for (int i = 0; i < N; ++i){ 
        a[i] = (a[i] ^ b[i]);
        printf(" %i", a[i]);
  } 
  printf("\n");
}

在 C 中,truefalse 的值分别是 10。这样就可以正常工作了。

但是你必须记住所有非零值都是"true"。因此,除非您有 true1,否则任何其他 "true" 值都不会执行按位运算所期望的操作。

示例:21 都是 "true",但是 2 & 1 而不是 "true" .

I have read online that I should not use bit-wise logic with bools. They appear to work here. Is this just luck of the draw with my compiler, or did I just misunderstand warnings about bitwise operators?

stdbool 的 bool 是标准 _Bool 类型的别名,标准声明它属于标准无符号整数类型。因此,_Bool 值是按位运算符的有效操作数,涉及它们的按位运算具有明确定义的结果。此外,当任何标量值转换为类型 _Bool 时,结果为 0 或 1,具体取决于原始值是否等于 0。

因此,如果您认为警告告诉您编译器可能会拒绝您的特定示例代码,或者生成的程序的行为可能与您使用 unsigned int 代替 _Bool,那么是的,你确实误解了警告。

正如其他人已经指出的那样,这更多是关于 non-_Bools 的布尔解释,而不是 _Bools 上的按位运算。具体来说,至少有一个操作数为非_Bool的按位运算结果的布尔解释不一定与相应逻辑运算的结果相同。