Reputation: 1300
Lately, I've been reading some code that has
if (! (a == b) )
instead of
if ( a != b )
in some places.
Obviously these are logically equivalent, but I'm wondering if there is any particular reason to use one over the other.
Are there certain circumstances where one is preferable, or is it all just a matter of personal style?
Upvotes: 4
Views: 1291
Reputation: 5629
This is the DeMorgan theorem. (Augustus De Morgan - Mathematician)
Go for if(a != b)
Upvotes: -5
Reputation: 1220
Any half-way decent compiler will put out the same code (unless == and != have been overloaded, as mentioned elsewhere) so optimization questions are irrelevant.
I don't think I've ever seen "if(!(a==b))" outside of a bigger conditional where it is clearer to not use DeMorgan's theorem, but I guess I could see it as a way of emphasizing that the two values really should be identical and there's something deeply wrong if they're not. However a honking big "throw OmgICantBelieveThisHappenedException()" on the next line would be even clearer. :-)
Other than these two situations I have to agree with the "use !=" camp since it's clearer when you skim the code. The '!' can be easily overlooked, especially with some formatting conventions.
Upvotes: 1
Reputation: 67822
As mentioned, languages with operator overloading often don't enforce a != for every ==. In this case, !( a == b ) is essential, as a != b is undefined. Furthermore, it may make sense in context to use !( a == b ). While the shorter form is preferred for the reasons given elsewhere in this question, the lengthier form can be more descriptive in certain problem sets.
Upvotes: 4
Reputation: 25147
I really prefer
if ( a != b )
simply because you are supposed to read less and you understand more quickly the message the programmer wanted to transmit.
Remember programmers spend more time reading code than writing it, so the more you can do to make code more understandable, the better.
Upvotes: 13
Reputation: 18266
Your code should be as simple as possible, ie less statements is better thus the a!=b is 3 constructs as opposed to ! (a=b) which is 4.
Upvotes: 1
Reputation: 101456
Mostly this is a matter of style (and my preference is for 'a != b'), but there could be an actual difference in operation if a is an object of a class that doesn't have either an operator== or an operator!=.
Upvotes: 9
Reputation: 405755
I would avoid
if (! (a == b) )
since it involves two operations, where there is one operator
if ( a != b )
that does the exact same thing. The second is also more readable (if only slightly).
The really big problem I have with
if (! (a == b) )
is that it made me stop and think "what the heck?" Good code shouldn't do that.
Upvotes: 6