Or are we all sticking to our taught \"&&, ||, !\" way?
Any thoughts in why we should use one or the other?
I\'m just wondering because several answe
Using these operators is harmful. Notice that and
and or
are logical operators whereas the similar-looking xor
is a bitwise operator. Thus, arguments to and
and or
are normalized to 0
and 1
, whereas those to xor
aren't.
Imagine something like
char *p, *q; // Set somehow
if(p and q) { ... } // Both non-NULL
if(p or q) { ... } // At least one non-NULL
if(p xor q) { ... } // Exactly one non-NULL
Bzzzt, you have a bug. In the last case you're testing whether at least one of the bits in the pointers is different, which probably isn't what you thought you were doing because then you would have written p != q
.
This example is not hypothetical. I was working together with a student one time and he was fond of these literate operators. His code failed every now and then for reasons that he couldn't explain. When he asked me, I could zero in on the problem because I knew that C++ doesn't have a logical xor operator, and that line struck me as very odd.
BTW the way to write a logical xor in C++ is
!a != !b