简体   繁体   中英

What's the difference between if(varName) and if(varName!=NULL)?

What's the difference between this:

if( varName != NULL ){
  // Do something
}

And:

if( varName ){
 // Do something
}  

I mean, is there a difference in terms of process speed? Or is only a better performance?

PD: I'm working with C.

There is no difference in case of performance, but the difference of intent might be significant. Assuming that NULL macro is defined as (void *) 0 , this code:

if( varName != NULL ) {
   // Do something
}

enforces that varName must be a pointer object. For instance, the following code would issue an error message:

int varName = 0;
if ( varName != NULL ) {
    // Do something
}

error: comparison between pointer and integer

Hence, this practice might be considered as sort of defensive programming , though its value is rather discussable, as both forms are equally idiomatic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM