为什么在比较变量之前将恒量? [英] Why put the constant before the variable in a comparison?
问题描述
我注意到了一段时间,现在在我们的一些code的语法如下:
I noticed for a while now the following syntax in some of our code:
if( NULL == var){
//...
}
或
if( 0 == var){
//...
}
和类似的东西。
有人能解释一下为什么当初是谁写的这个选择这种符号,而不是常见的 VAR == 0
办法的人)?
Can someone please explain why did the person who wrote this choose this notation instead of the common var == 0
way)?
它是一个风格问题,还是它在某种程度上影响性能?
Is it a matter of style, or does it somehow affect performance?
推荐答案
这是为了避免这样的错误的机制:
It's a mechanism to avoid mistakes like this:
if ( var = NULL ) {
// ...
}
如果您对右手边的变量名写出来,编译器将能够捕获某些错误:
If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes:
if ( NULL = var ) { // not legal, won't compile
// ...
}
当然,如果变量名称出现在等号的两侧,有些人觉得这种风格吸引力,这将不起作用。
Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing.
编辑:
由于埃文在评论中提到,任何像样的编译器会发出警告,如果启用了警告,例如的gcc -Wall
会给你以下内容:
As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, gcc -Wall
will give you the following:
warning: suggest parentheses around assignment used as truth value
您应该总是在你的编译器支持的警告,这是为了发现错误最便宜的方式。
You should always enable warnings on your compiler, it is the cheapest way to find errors.
最后,麦克乙组分出来,这是一个风格问题,并不会影响程序的性能。
Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.
这篇关于为什么在比较变量之前将恒量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!