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

后端 未结 12 743
难免孤独
难免孤独 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 07:03

    If the language is C and if p is a pointer then if (p) and if (!p) should be avoided.

    C (the language) doesn't specify that the null pointer will be boolean false. It does say that 0 casted to a pointer (either implicitly or explicitly) will give the null pointer.

    Therefore testing p rather than p == NULL are not necessarily the same, and on some older hardware they are definitely not the same since the null pointer is actually a pointer to a particular memory page.

    You can however guarantee that 0 and therefore NULL are equal to the null pointer, because C says they must be.

提交回复
热议问题