Why put the constant before the variable in a comparison?

笑着哭i 提交于 2019-12-17 19:33:41

问题


I noticed for a while now the following syntax in some of our code:

if( NULL == var){
   //...
}

or

if( 0 == var){
  //...
}

and similar things.

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?


回答1:


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.

Edit:

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.




回答2:


If you mistakenly put

if ( var = NULL )

instead of

if ( var == NULL )

then there will only be a compiler warning. If you reverse the order:

if ( NULL == var )

then there will be a compiler error if you put

if ( NULL = var )

Personally, I hate to read code written that way, and I only made that mistake once in my first year of coding. =)




回答3:


To avoid the

if (var = NULL)

bug




回答4:


Quoting Joel On Software, The Guerrilla Guide to Interviewing:

Occasionally, you will see a C programmer write something like if (0==strlen(x)), putting the constant on the left hand side of the == . This is a really good sign. It means that they were stung once too many times by confusing = and == and have forced themselves to learn a new habit to avoid that trap.

(I'm not really a fan of this "best practice".)




回答5:


Corollary: try to use const as much as you can.

const int val = 42;

if (val = 43) {
    ...
}

will not compile.




回答6:


Just by the way, I've observed over many years teaching C to new programmers that if you train yourself to read "=" as "gets" and "==" as equals, that in itself will save you from a lot of these bugs. Then you read

if( x = 0){

as "if x gets 0 then" and that begins to sound weird.




回答7:


Personally, I prefer

if (!x) {



来源:https://stackoverflow.com/questions/370366/why-put-the-constant-before-the-variable-in-a-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!