📄 faqcat1f1a.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN"><!-- This collection of hypertext pages is Copyright 1995-2005 by Steve Summit. --><!-- Content from the book "C Programming FAQs: Frequently Asked Questions" --><!-- (Addison-Wesley, 1995, ISBN 0-201-84519-9) is made available here by --><!-- permission of the author and the publisher as a service to the community. --><!-- It is intended to complement the use of the published text --><!-- and is protected by international copyright laws. --><!-- The on-line content may be accessed freely for personal use --><!-- but may not be published or retransmitted without explicit permission. --><!-- --><!-- this page built Sat Dec 24 21:47:45 2005 by faqproc version 2.7 --><!-- from source file null.sgml dated Wed Dec 21 13:03:25 2005 --><!-- corresponding to FAQ list version 4.0 --><html><!-- Mirrored from c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=null by HTTrack Website Copier/3.x [XR&CO'2008], Sat, 14 Mar 2009 07:57:40 GMT --><head><base ><meta name=GENERATOR content="faqproc"><title>Null Pointers</title></head><body bgcolor="#ffffff"><H1>5. Null Pointers</H1><a name="null1"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../null/null1.html"><!-- qtag -->Question 5.1</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What is this infamous null pointer, anyway?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>The language definition states that foreach pointer type,thereis a special value--the ``null pointer''--which isdistinguishable from allother pointer values andwhich is``guaranteed to compare unequal to a pointer toany object or function.''That is,a null pointer points definitively nowhere;it is not the address ofany object or function.Theaddress-of operator <TT>&</TT> will never yield a null pointer,nor will a successful call to<TT>malloc</TT>.<a href="../../null/nullsuccess.html" rel=subdocument>[footnote]</a>(<TT>malloc</TT>does returna null pointer when it fails,and this is a typical use of null pointers:as a ``special'' pointer value with some other meaning,usually ``not allocated'' or ``not pointing anywhere yet.'')</p><p>A null pointer is conceptually different from an uninitialized pointer.A null pointer is known not to point to any objector function;an uninitialized pointer might point anywhere.See also questions<a href="faqcatd3c2.html?sec=decl#initval">1.30</a>,<a href="faqcatbafd.html?sec=malloc#malloc1">7.1</a>,and<a href="faqcatbafd.html?sec=malloc#calloc">7.31</a>.</p><p>As mentioned above,there isa null pointer for each pointer type,and the internal values of null pointers fordifferent typesmay be different.Although programmers need not know the internal values, thecompiler must always be informed which type of null pointer is required,so that it can make the distinction if necessary(seequestions<a href="faqcat1f1a.html?sec=null#null2">5.2</a>,<a href="faqcat1f1a.html?sec=null#machnon0">5.5</a>,and<a href="faqcat1f1a.html?sec=null#safermacs">5.6</a>).</p><p>References:K&R1 Sec. 5.4 pp. 97-8<br>K&R2 Sec. 5.4 p. 102<br>ISO Sec. 6.2.2.3<br>Rationale Sec. 3.2.2.3<br>H&S Sec. 5.3.2 pp. 121-3<hr><hr><hr><a name="null2"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../null/null2.html"><!-- qtag -->Question 5.2</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How do I get a null pointer in my programs?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>With a <a href="../../sx1/index.html#null pointer constant"><dfn>null pointer constant</dfn></a>.</p><p>According to the language definition,an``integral constant expression with the value 0''in a pointer contextis converted into a null pointer at compiletime.That is, in aninitialization,assignment, or comparisonwhen one side is avariable or expressionof pointer type, the compiler can tell that a constant <TT>0</TT>on the other side requests a null pointer,and generate the correctly-typed null pointer value.Therefore, the following fragments are perfectly legal:<pre> char *p = 0; if(p != 0)</pre>(See also question <a href="faqcat1f1a.html?sec=null#ptrtest">5.3</a>.)</p><p>However, an argument being passed to a function is notnecessarilyrecognizable asa pointer context,and the compilermay not be able to tell that an unadorned <TT>0</TT> ``means''a nullpointer.To generate a null pointer in a function call context, anexplicit castmay berequired,to force the <TT>0</TT> to berecognized as a pointer.For example, theUnixsystem call<TT>execl</TT>takes avariable-length, null-pointer-terminated list of character pointer arguments,and is correctly called like this:<pre> execl("/bin/sh", "sh", "-c", "date", (char *)0);</pre>If the <TT>(char *)</TT> caston the last argumentwere omitted,the compiler would not know to pass a null pointer,and would pass an integer <TT>0</TT> instead.(Note that manyUnixmanualsget this example wrong;see also question <a href="faqcat1f1a.html?sec=null#nullreq">5.11</a>.)</p><p>When function prototypes are in scope, argument passing becomesan ``assignment context,''and most casts may safely be omitted,since the prototype tells thecompiler that a pointer is required,and of which type,enabling itto correctlyconvert an unadorned <TT>0</TT>.Function prototypes cannot provide the types for variablearguments in variable-length argument listshowever,so explicit casts are still required for those arguments.(See alsoquestion <a href="faqcat744e.html?sec=varargs#proto2">15.3</a>.)Itisprobablysafest toproperlycastall null pointerconstants in function calls,toguard against varargs functions or those without prototypes.</p><p>Here is a summary of the rulesfor whennull pointer constants may be used by themselves,and when they require explicit casts:<blockquote>[TABLE GOES HERE]</blockquote></p><p>References:K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192<br>K&R2 Sec. A7.10 p. 207, Sec. A7.17 p. 209<br>ISO Sec. 6.2.2.3<br>H&S Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171<hr><hr><hr><a name="ptrtest"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../null/ptrtest.html"><!-- qtag -->Question 5.3</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>Is the abbreviated pointer comparison ``<TT>if(p)</TT>'' to test fornon-null pointers valid?What if the internal representation for null pointers is nonzero?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>It is always valid.</p><p>When C requires the Booleanvalue of an expression,a false value isinferredwhen the expression comparesequal to zero, and a true value otherwise.That is, wheneverone writes<pre> if(expr)</pre>where``expr''is any expression at all, the compileressentially acts as if it had been written as<pre> if((expr) != 0)</pre>Substituting the trivial pointer expression``p''for``expr'',we have<pre> if(p) is equivalent to if(p != 0)</pre>and this is a comparison context, so the compiler can tellthat the (implicit) <TT>0</TT> is actually a null pointer constant,anduse the correct null pointer value.There is no trickery involved here;compilers do work this way,and generate identical code for both constructs.The internal representation of a null pointer does<em>not</em>matter.</p><p>The boolean negation operator, <TT>!</TT>, can be describedas follows:<pre> !expr is essentially equivalent to (expr)?0:1 or to ((expr) == 0)</pre>which leads to the conclusion that<pre> if(!p) is equivalent to if(p == 0)</pre></p><p>``Abbreviations'' such as <TT>if(p)</TT>,though perfectly legal<a href="../../null/assertptr.html" rel=subdocument>[footnote]</a>,are considered by some to be bad style(and by others to be good style;see question <a href="faqcataae2.html?sec=style#stylewars">17.10</a>).</p><p>See also question<a href="faqcate034.html?sec=bool#bool2">9.2</a>.</p><p>References:K&R2 Sec. A7.4.7 p. 204<br>ISO Sec. 6.3.3.3, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5<br>H&S Sec. 5.3.2 p. 122<hr><hr><hr><a name="macro"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../null/macro.html"><!-- qtag -->Question 5.4</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>What is <TT>NULL</TT> and how is itdefined?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>As a matter of style,many programmers prefer not to haveunadorned <TT>0</TT>'s scattered through their programs,some representing numbersand some representing pointers.Therefore, the preprocessor macro <TT>NULL</TT> isdefined(byseveral headers, including<TT><stdio.h></TT>and<TT><stddef.h></TT>)as a null pointer constant,typically<TT>0</TT>or <TT>((void *)0)</TT>(see also question <a href="faqcat1f1a.html?sec=null#safermacs">5.6</a>).A programmer who wishes to make explicit the distinction between<TT>0</TT> the integer and <TT>0</TT> the null pointer constantcan then use <TT>NULL</TT> whenever anull pointer is required.</p><p>Using <TT>NULL</TT>is a stylistic convention only; the preprocessor turns <TT>NULL</TT>back into<TT>0</TT> which is then recognized by the compiler,in pointer contexts,as before.In particular, a cast may still be necessary before <TT>NULL</TT> (asbefore <TT>0</TT>) in a function call argument.The table under question<a href="faqcat1f1a.html?sec=null#null2">5.2</a> above applies for<TT>NULL</TT> as well as <TT>0</TT>(an unadorned <TT>NULL</TT>is equivalent to an unadorned 0).</p><p><TT>NULL</TT>should be used<em>only</em>as a pointer constant;see question<a href="faqcat1f1a.html?sec=null#nullor0">5.9</a>.</p><p>References:K&R1 Sec. 5.4 pp. 97-8<br>K&R2 Sec. 5.4 p. 102<br>ISO Sec. 7.1.6, Sec. 6.2.2.3<br>Rationale Sec. 4.1.5<br>H&S Sec. 5.3.2 p. 122, Sec. 11.1 p. 292<hr><hr><hr><a name="machnon0"><h1>comp.lang.c FAQ list<font color=blue>·</font><a href="../../null/machnon0.html"><!-- qtag -->Question 5.5</a></h1><p><font face=Helvetica size=8 color=blue><b>Q:</b></font>How should <TT>NULL</TT> be defined on a machine which uses a nonzero bitpattern as the internal representation of a null pointer?</p><p><hr><p><font face=Helvetica size=8 color=blue><b>A:</b></font>The same asonany other machine: as <TT>0</TT>(or some version of <TT>0</TT>; see question <a href="faqcat1f1a.html?sec=null#macro">5.4</a>).</p><p>Whenevera programmer requests a null pointer,eitherby writing ``<TT>0</TT>'' or ``<TT>NULL</TT>'',it is the compiler'sresponsibilityto generatewhatever bit pattern the machine uses for that null pointer.(Again, the compiler can tell that an unadorned<TT>0</TT> requests a nullpointer when the <TT>0</TT> is in a pointer context;see question <a href="faqcat1f1a.html?sec=null#null2">5.2</a>.)Therefore, #defining <TT>NULL</TT> as <TT>0</TT> on a machine for which internalnull pointers are nonzero is as valid as on any other:the compiler mustalwaysbe able togenerate the machine's correctnull pointers in response tounadorned <TT>0</TT>'s seen in pointer contexts.A constant <TT>0</TT> is a null pointer constant;<TT>NULL</TT> is just a convenient name for it(see also question <a href="faqcat1f1a.html?sec=null#varieties">5.13</a>).</p><p>(Section 4.1.5 of the C Standard states that <TT>NULL</TT>``expands to an implementation-defined null pointer constant,''which means that the implementation gets to choosewhich form of <TT>0</TT> to useand whether touse a <TT>void *</TT> cast;see questions <a href="faqcat1f1a.html?sec=null#safermacs">5.6</a> and <a href="faqcat1f1a.html?sec=null#long0">5.7</a>.``Implementation-defined'' here does <em>not</em> meanthat <TT>NULL</TT> might be <TT>#define</TT>d to match someimplementation-specific nonzero internal null pointer value.)</p><p>See also questions<a href="faqcat1f1a.html?sec=null#null2">5.2</a>,<a href="faqcat1f1a.html?sec=null#macsochange">5.10</a>and <a href="faqcat1f1a.html?sec=null#machexamp">5.17</a>.</p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -