12

I didn't find one, but have a hard time believing there is none.

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335

2 Answers2

54

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

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 7
    I disagree. The expression `1!=2` evaluates to `true`, but `1 XOR 2` is very definitely false, since both 1 and 2 are `true`. To use the != operator as an XOR, you must cast to `bool` first. – IanPudney Jun 10 '13 at 13:06
  • 9
    @quinxorin: that's nonsense. I asked about _logical_ XOR, 1 and 2 aren't _logical_ values. In C++, logical means `bool`. – Violet Giraffe Jun 10 '13 at 13:08
  • 3
    I appear to have misunderstood your question. I didn't realize by "logical XOR" you meant that the values were already boolean. – IanPudney Jun 10 '13 at 13:12
  • 1
    I agree with @IanPudney. If you know both values are exactly either 0 or 1 (i.e. logical), then why not just use the `^` bitwise XOR operator? Using either `^` or `!=` will return incorrect results under the same conditions (when the values are not both exactly either 0 or 1). – Bill Hollings Jul 18 '16 at 15:52
  • ^ is an operation on integral values not logical values. 0 ^ 1 returns an int which is fine but so does true ^ false which can cause problems. ( true ^ false ) == true may give a compiler warning/error about comparing an int with a bool. This is why there is an & distinct from &&. For consistency there should be a ^^ – goneskiing Aug 10 '17 at 12:28
5

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)myVal)!=((bool)myOtherVal)
((bool)myVal)^((bool)myOtherVal)
//either works
IanPudney
  • 5,941
  • 1
  • 24
  • 39