为什么在比较中将常量放在变量之前?

2021-12-29 00:00:00 c comparison syntax c++

我注意到我们的一些代码中的以下语法有一段时间了:

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.

正如 Evan 在评论中提到的,如果您启用警告,任何体面的编译器都会警告您这一点,例如,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.

最后,正如 Mike B 所指出的,这是一个风格问题,不会影响程序的性能.

Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.

相关文章