There is one technical reason in C++, and that is because if you have a habit of using ==
over !=
, you won't need to overload as many operators.
This matters when you are dealing with function objects ("functors"). For example when you use a standard container class to store your own custom objects and want to have them automatically sorted. In order for the function object (for example std::equal_to) to work, your class needs to overload the ==
operator only. You don't have to overload ==
and !=
both.
Similarly, other function objects require that you only overload <
and not all of < > == != <= >=
.
Generally, negations are not easy for the human brain to comprehend. Particularly if you have double negations. It is custom in most programming languages to write the equality check first, if the order doesn't matter technically. Most often it makes the code easier to read.
But as often with programming and coding style, there is no black or white rules. If the reason for the check is to find an error, then the most readable way to write error handling take precedence over "humans find negations harder to read".
Consider this not too well-written code:
if(input == good)
{
if(format == expected)
{
do_stuff();
return ok;
}
else
{
return error_format;
}
}
else
{
return error_input;
}
Imagine we need to add even more error handling to this. Quite a common case: suppose we are writing a parser or some data protocol decoder with lots of error handling. The multiple levels of nested braces soon would turn the code into a complete mess.
We can get rid of the need to have nested if statements if we change from == to !=.
if(input != good)
{
return error_input;
}
if(format != expected)
{
return error_format;
}
// if we got here then all is well
do_stuff();
return ok;
This will be much more readable and scale well if we need to add more error checks. So by changing to != we made the code more readable.