Logical XOR operator in C++?
Is there such a thing? It is the first time I encountered a practical need for it, but I don't see one listed in Stroustrup. I intend to write:
// Detect when exactly one of A,B is equal to five.
return (A==5) ^^ (B==5);
But there is no ^^
operator. Can I use the bitwise ^
here and get the right answer (regardless of machine representation of true and false)? I never mix &
and &&
, or |
and ||
, so I hesitate to do that with ^
and ^^
.
I'd be more comfortable writing my own bool XOR(bool,bool)
function instead.
!=
运算符为bool
值提供此目的。
对于真正的逻辑异或操作,这将起作用:
if(!A != !B) {
// code here
}
Proper manual logical XOR implementation depends on how closely you want to mimic the general behavior of other logical operators ( ||
and &&
) with your XOR. There are two important things about these operators: 1) they guarantee short-circuit evaluation, 2) they introduce a sequence point, 3) they evaluate their operands only once.
XOR evaluation, as you understand, cannot be short-circuited since the result always depends on both operands. So 1 is out of question. But what about 2? If you don't care about 2, then with normalized (ie bool
) values operator !=
does the job of XOR in terms of the result. And the operands can be easily normalized with unary !
, if necessary. Thus !A != !B
implements the proper XOR in that regard.
But if you care about the extra sequence point though, neither !=
nor bitwise ^
is the proper way to implement XOR. One possible way to do XOR(a, b) correctly might look as follows
a ? !b : b
This is actually as close as you can get to making a homemade XOR "similar" to ||
and &&
. This will only work, of course, if you implement your XOR as a macro. A function won't do, since the sequencing will not apply to function's arguments.
Someone might say though, that the only reason of having a sequence point at each &&
and ||
is to support the short-circuited evaluation, and thus XOR does not need one. This makes sense, actually. Yet, it is worth considering having a XOR with a sequence point in the middle. For example, the following expression
++x > 1 && x < 5
has defined behavior and specificed result in C/C++ (with regard to sequencing at least). So, one might reasonably expect the same from user-defined logical XOR, as in
XOR(++x > 1, x < 5)
while a !=
-based XOR doesn't have this property.
下一篇: C ++中的逻辑XOR运算符?