使用IF语句时是否有正确或错误的做法:if(foo)或if(foo == true)? [英] Is there a right or wrong practice when using IF statements : if(foo) or if(foo == true)?

查看:366
本文介绍了使用IF语句时是否有正确或错误的做法:if(foo)或if(foo == true)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的(短期)职业生涯迄今为止的编程(仅仅是一名从事实习的学生)中,我注意到在IF语句方面,有两种不同的方式。

Throughout my (short) career so far in programming (merely a student working on internship) I have noticed that when it comes to IF statements, there is two different ways of doing it.

如果我们将 foo 作为布尔值:

If we take foo as a boolean value:

if(foo)
{
    //do stuff
}

这是我处理IF语句时的首选方式,如果我正在寻找假的我使用:

This is my preferred way of doing things when dealing with IF statements, if I'm looking for false I use:

if(!foo)
{
    //do more stuff
}

然而,当有些人看到这个时,他们会抬起眉毛,暗示我可能会陷入一种坏习惯。但我想知道,这种方式或典型方式有什么区别吗?

However, when some people see this they raise an eyebrow, suggesting that I may be stuck in a bad habit. But I wanted to know, is there any difference between this way or the "typical" way?

if(foo == true)
{
    //do a bit more stuff
}

我是否会陷入新程序员的共同陷阱?或者没有区别(至少是一个明显的差异)

Am I falling into a common trap for new programmers? Or is there no difference (at least a noticeable one)

推荐答案

我从不写== true或== false。在我看来,它违背了if-sentence的观点。

I never write == true or == false. It goes against the point of an if-sentence, in my opinion.

如果是基本的:如果布尔表达式为真,则执行某些操作。布尔值是一个布尔表达式本身,所以为什么要包装它?

an if is basicly: If a Boolean expression is true, do something. a Boolean is a boolean expression in and of itself, so why wrap it?

所以在我看来,使用== true的那些是有坏习惯的。因为他们对语言的工作原理一无所知。

So in my opinion, the ones using == true are the ones with a bad habit. Becuase they display ignorance of how the language works.

想想这些允许的写法,如果(Foo)和if(!Foo):

think of these "allowed" ways to write if (Foo) and if (!Foo):

if (Foo == true) //If Foo is the same as true
if (Foo != true //If Foo is not the same as true
if (Foo != false) //if Foo is not the same as false
if (Foo == false) //If Foo is the same as false
if (Foo) //If Foo
if (!Foo) //If not Foo

使用==和!=与布尔实际上在编程和阅读代码时会引入新的错误方法。

using == and != with booleans actually introduce new ways to make mistakes both when programming and reading code.

布尔和布尔很难被误读。

Boolean and !Boolean is hard to misread.

这篇关于使用IF语句时是否有正确或错误的做法:if(foo)或if(foo == true)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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