Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a pragmatic reason to use "if (0 == p) " instead of "if (!p)"?

I'm inclined to write if statements by using logical negation operator:

if (!p)
    some_code();

Some people around me tend to use explicit comparison, so that the code looks like:

if (FOO == p)
    some_code();

where FOO is one of false, FALSE, 0, 0.0, NULL, etc.

I prefer the short form because it is:

  • operator!= friendly
  • generic programming friendly
  • laconic (and even more beautiful, as for me)

What are the pragmatic benefits of writing this otherwise (if any)?

like image 434
Andrey Avatar asked Mar 03 '11 22:03

Andrey


4 Answers

To contrast @Erik's answer I would say use ! for readability. If you find you are overlooking it then get your eyes tested. What's next? Avoid 1, use 3 - 2 instead?

like image 105
Troubadour Avatar answered Oct 26 '22 02:10

Troubadour


Use (0 == p) or (p == 0) for readability. That ! is easier to overlook at first glance than == 0

Use (0 == p) if you have a habit of ignoring compiler warnings, and want to know when you use = rather than ==.

like image 43
Erik Avatar answered Oct 26 '22 04:10

Erik


It depends on what p represents.

If p represents a boolean/logical value, then (!p) seems most appropriate - comparing to "FALSE" is generally discouraged. I don't anticipate this being of much debate.

If p represents a value, like a counter, then (p == 0) or (0 == p) seems appropriate. (There is usually a hot debate between the two. I find the first more readable, but the second avoids some very serious bugs.) Aside from which of the two options is better, I don't anticipate this being a debate (as in, it should compare to 0.)

If p represents a pointer, then you have some issues. A competent C++ programmer should know that (!p) will tell you if it's null or not. However, the idea of the readability of this is a grey area, and I see this being a highly contested debate.

like image 21
corsiKa Avatar answered Oct 26 '22 03:10

corsiKa


Some claim that the pragmatic benefit is that programmers will find it easier to understand if you explicitly compare against NULL, FALSE, 0, etc., whereas the logical operator may be confusing to people who don't understand how implicit conversions and booleans work in C/C++.

(Disclaimer: I don't share this view myself. if (p) ... and if (!p)... are the idiomatic ways to express this in C and C++, and programmers who have trouble understanding them have no business touching C or C++ code. Heath Hunnicutt's comment is dead on.)

like image 41
Kristopher Johnson Avatar answered Oct 26 '22 02:10

Kristopher Johnson