I\'m inclined to write if statements by using logical negation operator:
if (!p)
some_code();
Some people around me tend to use explicit co
With if (0 == p)
you force the comparison to enter that "if scope" in that case. I mean, it will be clear that you want to do that in case p is equals 0
. By just using (!p)
its not explicit what you want to know. It could be null, false
, etc.
the only pragmatic reason i see there is that in the second case the type of values considered for comparison is more explicit (es. foo == null foo is a ponter type, !foo can't say if it is a pointer, a bool, etc)
In a really complex conditional, using an explicit == can help make it more readable. Unfortunately, it also opens the door for writing x = 0 instead of x == 0, but you can avoid this by writing 0 == x instead(so that 0 = x will throw an error).
It could also be habit from other languages where you'd have to cast to a boolean otherwise.
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.
if (Foo)
and if (!Foo)
seem to imply Foo
is a boolean variable, at least for me. That being said, as long as your identifier is sufficiently descriptive it really shouldn't matter. I would use !Foo
for new code, but follow existing conventions if there are any. Consistency trumps all.
I would place a space before and after !: ( ! p)
so ! stands out. But I would restrict this usage to only integer types including pointers. I would use ==
for floating points because it will cause you and others to pause and think if 0.0 == p
is really appropriate versus specifying a tolerance.
If p is an instance of a class, ( ! p)
should be used by defining operator! to avoid an implicit conversion with 0.0 == p
.