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

后端 未结 12 749
难免孤独
难免孤独 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: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.

提交回复
热议问题