Friday, July 10, 2009

Why test for inequality is better than test for equality

The coding standard which we follow suggested us to use test for inequality rather than test for equality.

It suggests we should go for if (func() != FALSE) rather than if (func() == TRUE) {...

I didn't know what the exact reason for this to be followed. It shouldn't be anything related to optimization. I was looking for the answer for some time now. Well found this snippet in a site. Here is the logic behind it....


Test for true or false
Do not default the test for non-zero, that is:
if (f() != FAIL)

is better than
if (f())

Even though FAIL may have the value 0 which C/C++ considers to be false. (Of course, balance this against constructs such as the one shown above in the "Function Names" section.) An explicit test will help you out later when somebody decides that a failure return should be -1 instead of 0.

Do not check a boolean value for equality with 1 (TRUE, YES, etc.); instead test for inequality with 0 (FALSE, NO, etc.). Most functions are guaranteed to return 0 if false, but only non-zero if true. Thus,
if (func() == TRUE) {...

is better written
if (func() != FALSE)

No comments: