I need to do an xor conditional between 3 values, ie i need one of the three values to be true but not more than one and not none.
I thought i could use the xor ^ op
XOR is a binary operator, it can only be used on 2 values at a time. So when you do (true XOR true XOR true)
, it actually does ((true XOR true) XOR true)
...
The inner (true XOR true)
resolves to false
because they're the same. With that resolved, the remainder is (false XOR true)
, which resolves to true
.
It sounds like you're trying to be clever or super-efficient about matching your conditions. This would probably take me several minutes to puzzle out and then write a truth-table or test to make sure it treats all possible combinations correctly.
It is so much simpler to just count how many of them are true
and do if (countTrues == 1)
. The reason for this is that it doesn't have significant overhead, and it is actually readable and understandable compared to a solution using only bit-twiddling (there are a couple other answers here that demonstrate it).