Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use the xor operator for boolean checks? [closed]

People also ask

What is the rule for the XOR operation?

) from mathematical logic; that is, a true output results if one, and only one, of the inputs to the gate is true. If both inputs are false (0/LOW) or both are true, a false output results. XOR represents the inequality function, i.e., the output is true if the inputs are not alike otherwise the output is false.

Is XOR a Boolean operator?

XOR is one of the sixteen possible binary operations on Boolean operands. That means that it takes 2 inputs (it's binary) and produces one output (it's an operation), and the inputs and outputs may only take the values of TRUE or FALSE (it's Boolean) – see Figure 1.

What does XOR mean in Boolean?

(eXclusive OR) A Boolean logic operation that is widely used in cryptography as well as in generating parity bits for error checking and fault tolerance. XOR compares two input bits and generates one output bit. The logic is simple. If the bits are the same, the result is 0. If the bits are different, the result is 1.

Is XOR the same as not equal?

For Boolean values, they mean the same thing - although there's a compound assignment operator for XOR: x ^= y; There's no equivalent compound assignment operator for inequality.


You can simply use != instead.


I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.

If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.


I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.

My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.

As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.


I think it'd be okay if you commented it, e.g. // ^ == XOR.