问题
I have a toy program in which I use the <stdbool.h>
library to use the type bool
. I have a few arrays of bool
's, and the following commands work in a loop.
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?
#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");
}
回答1:
In C the values for true
and false
are 1
and 0
respectively. So that will work fine.
However you have to remember that everything non-zero is "true". So unless you have true
or 1
, any other "true" value is not going to do what you expect using bitwise operations.
Example: Both 2
and 1
are "true", but 2 & 1
will not be "true".
回答2:
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's bool
is an alias for the standard _Bool
type, which the standard declares to be among the standard unsigned integer types. As a result, _Bool
values are valid operands for the bitwise operators, and bitwise operations involving them have well-defined results. Moreover, when any scalar value is converted to type _Bool
, the result is either 0 or 1, depending on whether the original value compares equal to 0.
Thus, if you thought the warnings were telling you that a compiler might reject your particular example code, or that the resulting program might behave differently than if you used, say, unsigned int
in place of _Bool
, then yes, you did misunderstand the warnings.
As others have already remarked, this is more about the boolean interpretation of non-_Bool
s than about bitwise operations on _Bool
s. Specifically, the boolean interpretation of the result of a bitwise operation in which at least one of the operands is a non-_Bool
is not necessarily the same as the result of the corresponding logical operation.
来源:https://stackoverflow.com/questions/48588556/bitiwise-exclusive-or-with-stdbool-h-bool-types-in-c-and-assignment