gpt4 book ai didi

c++ - 为什么 C/C++ 中没有 ^^ 运算符?

转载 作者:IT老高 更新时间:2023-10-28 22:15:35 24 4
gpt4 key购买 nike

&&&|||。为什么^没有^^

我知道它不会短路,但它会有不同的语义。在 C 中,true 实际上是任何非零值。按位异或并不总是与逻辑异或相同:

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)

既然你不能总是依赖一个真正的值是 1-1,那么 ^^ 运算符不是很好吗有帮助吗?我经常不得不做这样奇怪的事情:

if(!!a ^ !!b) // looks strange

最佳答案

Dennis Ritchie answers

There are both historical and practical reasons why there is no ^^ operator.

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() ^^ ...) ...

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/C++ 中没有 ^^ 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/837265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com