C 或 C++ 标准库中是否有逻辑(布尔)XOR 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17024355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a logical (boolean) XOR function in C or C++ standard library?
提问by Violet Giraffe
I didn't find one, but have a hard time believing there is none.
我没有找到,但很难相信没有。
回答by Matt Ball
Boolean XOR is the same thing as !=
, "not equal."
布尔异或与!=
“不等于”是一回事。
p | q | p != q
--+---+-------
F | F | F
T | F | T
F | T | T
T | T | F
http://en.wikipedia.org/wiki/Truth_table#Logical_conjunction
http://en.wikipedia.org/wiki/Truth_table#Logical_conjunction
回答by IanPudney
If you're looking for whether two values are identical, you can use !=
or the bitwise operator ^
. You can use this if your values are already bool
. However, if your values are not purely bool
, cast them to bool
first:
如果您正在寻找两个值是否相同,您可以使用!=
或 按位运算符^
。如果您的值已经是 ,则可以使用它bool
。但是,如果您的值不完全是bool
,请将它们转换为bool
第一:
((bool)myVal)!=((bool)myOtherVal)
((bool)myVal)^((bool)myOtherVal)
//either works