In C++, the logical operators &&
, ||
, !
are there, which corresponds to conjunction , disjunction
, negation
, respectively.
But I noticed the comparison operators ==
, !=
, <
, >
, <=
, >=
can be used for booleans as well! Given that P
and Q
are booleans:
P == Q
is bicontitional ,
P != Q
is exclusive disjunction ,
P < Q
is converse nonimplication ,
P > Q
is nonimplication ,
P <= Q
is implication ,
And P >= Q
is converse implication .
My questions are:
Will the program perform better by this trick?
Is there any example code using this trick (in any language)?
Will the performance increase by this trick?
On any processor where it would have any benefit, when P
and Q
are simple variables, this would be simple enough that you should expect compilers to make use of it already without requiring any source code rewriting.
But keep in mind that P < Q
in general has a distinct disadvantage over !P && Q
: it requires evaluation of Q
, when the result is already known if P
evaluates to true
. The same applies to all the other relational operators.
Is there any example code using this trick (in any language)?
Not as a trick, but because it arguably leads to code that's easier to understand (not any specific language):
if ((a == null) != (b == null))
throw "a and b must either both be null, or both be non-null";
It could be written with ^
. Which is easier to read is a matter of opinion.