Search code examples
cperformancenullcomparison

C: Comparison to NULL


Religious arguments aside:

  • Option1:

    if (pointer[i] == NULL) ...
    
  • Option2:

    if (!pointer[i]) ...  
    

In C is option1 functionally equivalent to option2?

Does the later resolve quicker due to absence of a comparison ?


Solution

  • I like the second, other people like the first.

    Actually, I prefer a third kind to the first:

    if (NULL == ptr) {
       ...
    }
    

    Because then I:

    • won't be able to miss and just type one =
    • won't miss the == NULL and mistake it for the opposite if the condition is long (multiple lines)

    Functionally they are equivalent.

    Even if a NULL pointer is not "0" (all zero bits), if (!ptr) compares with the NULL pointer.

    The following is incorrect. It's still here because there are many comments referring to it: Do not compare a pointer with literal zero, however. It will work almost everywhere but is undefined behavior IIRC.