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
"What's in a name? That which we call &&, || or ! By any other name would smell as sweet."
In other words, natural depends on what you are used to.
It's nice to use 'em in Eclipse+gcc, as they are highlighted. But then, the code doesn't compile with some compilers :-(
In cases where I program with names directly mapped to the real world, I tend to use 'and' and 'or', for example:
if(isMale or isBoy and age < 40){}
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
I like the idea of the not
operator because it is more visible than the !
operator. For example:
if (!foo.bar()) { ... }
if (not foo.bar()) { ... }
I suggest that the second one is more visible and readable. I don't think the same argument necessarily applies to the and
and or
forms, though.
So to summarize: it's not used a lot because of following combination
Thanks for your thoughts