Is there any particular reason for !=
to be used more than ==
?
I have noticed that !=
seems more common, but wondered if there was a reason for this.
Is there any particular reason for !=
to be used more than ==
?
I have noticed that !=
seems more common, but wondered if there was a reason for this.
If you have code like this:
if (a == b)
{
// block 1
}
else
{
// block 2
}
It can be rewritten as:
if (a != b)
{
// block 2
}
else
{
// block 1
}
These two examples do the same thing. Neither is more efficient than the other. If one is used more than the other it may be personal preference.
You should use ==
or !=
according to the logical condition you are trying to express. If you care about both the true
and false
conditions, i.e. both the if
and else
parts then the net effect of switching (if it's a simple comparison) is just which code needs to appear in which part.
There is a coding style, see (the book) Code Complete's section on Forming Boolean Expressions Positively which suggests that boolean expressions that express something positive are easier to understand than those expressing something negative.
If you only care about the condition when it evaluates to true
, e.g. you only care when you have equality (for ==
) or do not have equality (for !=
) then you'll not require an else
section if you pick the correct one.
Most of the time the preference of using != or == will depend on the content:
resultOfOperationOrCall = operationOrCall(...);
if (resultOfOperationOrCall != somePredefinedErrorTypeValue) {
// Normal processing
} else {
// Exception/error processing
}
Here using != is logically clearer than using ==
I prefer !=
because it's more explicit (and there is less chances to write =
as mistake).
As assembly code for both == and != present so no issue of efficient or inefficient code for x86 architecture.So it is up to you .you can use any one of them.
if for some machine if assembly code not available then efficient or inefficient comes it to picture as that is achieved by compiler by performing some additional operation(that is adding additional assembly code).
Its wholly and solely depends on the perception & need of user. I don't see any reason on why would one use != more than ==