Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>NULL</code> is guaranteed to be zero, perhaps casted to <code>(void *)</code><sup>1</sup>.</p> <p>C99, §6.3.2.3, ¶3</p> <blockquote> <p>An integer constant expression with the value <code>0</code>, or such an expression cast to type <code>void *</code>, is called a null pointer constant.(55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.</p> </blockquote> <p>And note 55 says:</p> <blockquote> <p>55) The macro NULL is defined in <code>&lt;stddef.h&gt;</code> (and other headers) as a null pointer constant.</p> </blockquote> <p>Notice that, because of how the rules for null pointers are formulated, the value you use to assign/compare null pointers is guaranteed to be zero, but the bit pattern actually stored inside the pointer can be any other thing (but AFAIK only few very esoteric platforms exploited this fact, and this should not be a problem anyway since to "see" the underlying bit pattern you should go into <a href="http://en.wikipedia.org/wiki/Undefined_behavior">UB</a>-land anyway).</p> <hr /> <p>So, as far as the standard is concerned, the two forms are equivalent (<code>!ptr</code> is equivalent to <code>ptr==0</code> due to §6.5.3.3 ¶5, and <code>ptr==0</code> is equivalent to <code>ptr==NULL</code>); <code>if(!ptr)</code> is also quite idiomatic.</p> <p>That being said, I usually write explicitly <code>if(ptr==NULL)</code> instead of <code>if(!ptr)</code> to make it extra clear that I'm checking a pointer for nullity instead of some boolean value.</p> <hr /> <ol> <li>Notice that in C++ the <code>void *</code> cast cannot be present due to the stricter implicit casting rules that would make the usage of such <code>NULL</code> cumbersome (you would have to explicitly convert it to the compared pointer's type every time).</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload