When to use == 0

This is no longer a debate in the Linux kernel, but I saw some code written in out of date style recently and it was a moment of reminiscing. You used to see code like this:

ret = frob();
if (ret != 0)
return ret;

You should never use == NULL or != NULL. This rule is enforced by checkpatch. Comparing against zero is more subtle because there are a few situations where == 0 and != 0 is appropriate.

One place where == comparisons with zero is appropriate is for NUL terminators. Always test against “if (*p == ‘\0’)”. Don’t use ‘if (!*p)” and especially don’t use “if (*p == 0)”. NUL terminators are really important and they are their own thing. Make them stand out. Don’t take short cuts.

Another time to use to use == comparisons is with enums. Don’t say if (!direction). Say if (direction == READ)”.

In the example code at the start of this blog, “ret” is not a number like 1, 2, 3, etc. “ret” means is there an error code or not? It should just be written as”if (ret) “. Some people think “if (ret != 0) is more readable. But then I used to tell them to make it even more readable by writing “if (ret != 0 != 0)”. I still remember this as being the wittiest thing I have ever said in my life and it’s the reason why this blog entry exists.

If you have a condition like “if (len == 0) “. That’s perfectly fine and readable. To be honest, “if (!len)” is also okay. In this situation a zero length has a special negative meaning of absence. Zero length is different from every other length. I would probably write the former rather than the latter but only a nutter would complain either way.

The place where I would complain is if there is no special meaning of absence. For example, the first element in an array is not different from the second element. It should be “if (index == 0) “. This is especially true if there are other tests on the same variable. Don’t write “if (!value) … else if (value == 1) … else if (value == 2). Use == 0, == 1 and == 2 consistently.

The final time to use == 0 is for strcmp() type functions. In those functions, you’re comparing two strings. The strcmp() functions return < 0 if the first parameter is less than the second. They return > 0 if the first parameter is greater than the second. And they return == 0 if the parameters are equal. Once you know that then “if (strcmp(a, b) == 0)” is very readable. Writing it as “if (!strcmp(a, b))” is so awkward.

Leave a comment

Design a site like this with WordPress.com
Get started