为什么如果(恒定的==变量)是pferred,而不是如$ P $(可变==常数) [英] Why if( constant == variable ) is preferred instead of if ( variable == constant )
问题描述
可能重复:结果
如何检查等号? (0 == i)或(ⅰ== 0)的结果
<一href=\"http://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c\">Why做一件经常看到&ldquo;!=空可变的rdquo;的而不是&ldquo;!变量=空&rdquo;的在C#中?结果
<一href=\"http://stackoverflow.com/questions/3309089/why-do-some-experienced-programmers-write-ex$p$pssions-this-way\">Why做一些有经验的程序员编写的前pressions这样?结果
NULL是什么意思!=在C ++中的价值?一>
Possible Duplicate:
How to check for equals? (0 == i) or (i == 0)
Why does one often see “null != variable” instead of “variable != null” in C#?
Why do some experienced programmers write expressions this way?
What is the meaning of NULL != value in C++?
例如,
int k =5;
if( 5 == k )
{
}
是preferred过
is preferred over
if (k == 5)
{
}
时只考虑格式化的目的还是有它背后的原因吗?
Is it considered only for formatting purpose or is there any reason behind it?
推荐答案
由于这种形式使得它更难被遗忘的等号一一介绍的错误。试想一下,如果你这样做:
Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:
if (k = 5)
这是打算作为比较,但它现在是一个任务!更糟的是,它的法律的,它会弄乱你的多种方式的程序(的 K
被改变,和条件始终评估值到真正
)。
This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k
is changed, and the conditional always evaluates to true
).
与
if (5 = k)
这是不合法的(你不能分配到一个文本),所以编译器会立即将其标记为错误。
This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.
这是说,写作code的这种风格(条件语句内分配)并不像prevalent今天因为它曾经是。大多数现代编译器会将此作为一个警告,所以它不可能不被发现。我个人不喜欢第二形式,因为编译器有帮助,我不使用它。
That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it's unlikely to go undetected. Personally I don't like the second form and since the compiler is there to help I don't use it.
这篇关于为什么如果(恒定的==变量)是pferred,而不是如$ P $(可变==常数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!