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
friendlyWhat are the pragmatic benefits of writing this otherwise (if any)?
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?
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 ==.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With