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

标签 c++ c operators language-design xor

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

我知道它不会短路,但它会有不同的语义。在 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/

相关文章:

c++ - Type Traits - 显式模板特化。在 xcode 上失败

java - 如何使用 Java 在 KieServices 中以编程方式注册 Drools 6 自定义运算符

将文本转换为二进制文件

c - 在使用 pthreads 的 C 语言中,如何让某个线程运行直到达到某个值?

c++ - boost foreach 和运算符重载

python - PyTorch 中 "*"运算符在张量大小之前做什么?

c++ - MFC 应用程序的测试框架

c++ - C++编译时的静态字符数组大小

.net - 从非托管 C++ 动态加载混合模式 C++/CLI .dll(和依赖项)

C 嵌套 union 和结构