为什么在C / C ++中没有^^运算符? [英] Why is there no ^^ operator in C/C++?
问题描述
&
有&&
。 |
有 ||
。为什么 ^
有 ^^
?
&
has &&
. |
has ||
. Why doesn't ^
have ^^
?
我理解它不会是短路的,但它会有不同的语义。在C中, true
实际上是任何非零值。位异或不总是与逻辑XOR相同的:
I understand that it wouldn't be short-circuiting, but it would have different semantics. In C, true
is really any non-zero value. Bitwise XOR is not always the same thing as logical XOR:
int a=strcmp(str1,str2);// evaluates to 1, which is "true"
int b=strcmp(str1,str3);// evaluates to 2, which is also "true"
int c=a ^^ b; // this would be false, since true ^ true = false
int d=a ^ b; //oops, this is true again, it is 3 (^ is bitwise)
t总是依赖于 1
或 -1
的真值,不会是 ^ ^
操作符是非常有帮助?我经常要做这样奇怪的事情:
Since you can't always rely on a true value being 1
or -1
, wouldn't a ^^
operator be very helpful? I often have to do strange things like this:
if(!!a ^ !!b) // looks strange
推荐答案
有历史和实际的原因,为什么没有
^^
运算符。
实用的是:操作员没有太多的用处。 &&
和 ||
的要点是利用它们的短路评估,
[...]
相反, ^^
操作符总是强制评估表达式的两个臂,因此没有效率增益。此外, ^^
真正被调用的情况是非常罕见的,虽然可以创建示例。当你堆栈运算符时,这些情况变得稀少和陌生。
The practical is: there's not much use for the operator. The main point of &&
and ||
is to take advantage of their short-circuit evaluation not only for efficiency reasons, but more often for expressiveness and correctness.
[...]
By contrast, an ^^
operator would always force evaluation of both arms of the expression, so there's no efficiency gain. Furthermore, situations in which ^^
is really called for are pretty rare, though examples can be created. These situations get rarer and stranger as you stack up the operator--
if (cond1() ^^ cond2() ^^ cond3() ^^ ...) ...
condx()
s为真。相比之下,&&
和 ||
类似物仍然相当合理和有用。
does the consequent exactly when an odd number of the condx()
s are true. By contrast, the &&
and ||
analogs remain fairly plausible and useful.
这篇关于为什么在C / C ++中没有^^运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!