Search code examples
cif-statementzero

c if statement check for zero


Is it recommended in c to write conditionals like this

if(foo != 0) {
    // do stuff
}

Or like this

if(foo) {
  // do stuff
}

I know they will always produce the same result, but which method is recommended for readability?


Solution

  • Consider the various types that foo may have. What is best is context sensitive.

    I favor the first in each group.

    void *fooptr = bar();
    if (fooptr) ...
    if (fooptr != NULL) ...
    if (fooptr != 0) ...
    
    int fooi = bar();
    if (fooi != 0) ...
    if (fooi) ...
    
    double foofp = bar();
    if (foofp != 0.0) ...
    if (foofp) ...
    
    bool foobool = bar();
    if (foobool) ...
    
    int (*foofun)() = bar();
    if (foofun) ...
    if (foofun != NULL) ...
    if (foofun != 0) ...
    

    But avoid foolish ones

    if (foobool == 0.0) ...
    if (fooi != NULL) ...
    

    And I did not even touch the Yoda style (trying to avoid a holy war)

    if (0 == foo) ...
    

    In general, seeing code in the positive sense if(foo) vs. if (foo != 0), is conceptually simpler. And I prefer if(foo == NULL) to if(!foo)

    You not think it isn't less understandable to avoid negating negatives, no?