Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...