有一个务实的理由使用“if(0 == p)”。而不是“if(!p)”? [英] is there a pragmatic reason to use "if (0 == p) " instead of "if (!p)"?

查看:115
本文介绍了有一个务实的理由使用“if(0 == p)”。而不是“if(!p)”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于使用逻辑否定运算符写if语句:

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();

其中FOO是 false FALSE 0 0.0 NULL 等。

where FOO is one of false, FALSE, 0, 0.0, NULL, etc.

因为它是:


  • operator!= 友好

  • 通用程式设计友好

  • 简明(甚至更漂亮)

  • operator!= friendly
  • generic programming friendly
  • laconic (and even more beautiful, as for me)

否则(如果有的话)务实的好处是什么?

What are the pragmatic benefits of writing this otherwise (if any)?

推荐答案

有人声称,实用的好处是程序员会发现它更容易理解,如果你显式比较NULL,FALSE,0等,而逻辑运算符可能会让那些不明白隐式转换和布尔在C / C ++中如何工作的人感到困惑。

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++.

(免责声明:我不自己共享此视图。 if(p)... if(!p)... 是表达这个的惯用方式C和C ++,而程序员在理解它们时遇到麻烦,没有涉及C或C ++代码的业务。 Heath Hunnicutt的评论已经死了。)

(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(0 == p)”。而不是“if(!p)”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆