Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 225
Ande Turner Avatar asked Aug 16 '09 11:08

Ande Turner


People also ask

Can you compare to null in C?

In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.

What is null equal to C?

Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

How do you compare a value to null?

SQL has the is [not] null predicate to test if a particular value is null . With is [not] distinct from SQL also provides a comparison operator that treats two null values as the same. Note that you have to use the negated form with not to arrive at similar logic to the equals ( = ) operator.

Can we compare the value with null?

The value NULL does not equal zero (0), nor does it equal a space (' '). Because the NULL value cannot be equal or unequal to any value, you cannot perform any comparison on this value by using operators such as '=' or '<>'.


1 Answers

I prefer the explicit style (first version). It makes it obvious that there is a pointer involved and not an integer or something else but it's just a matter of style.

From a performance point of view, it should make no difference.

like image 144
Laserallan Avatar answered Sep 19 '22 06:09

Laserallan