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

后端 未结 12 741
难免孤独
难免孤独 2021-02-05 06:18

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

相关标签:
12条回答
  • 2021-02-05 06:52

    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.

    0 讨论(0)
  • 2021-02-05 06:53

    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)

    0 讨论(0)
  • 2021-02-05 06:54

    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.

    0 讨论(0)
  • 2021-02-05 06:57

    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.

    0 讨论(0)
  • 2021-02-05 06:57

    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.

    0 讨论(0)
  • 2021-02-05 07:03

    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.

    0 讨论(0)
提交回复
热议问题