Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site sfmag.UUCP Path: utzoo!watmath!clyde!burl!ulysses!sfmag!mjs From: mjs@sfmag.UUCP (M.J.Shannon) Newsgroups: net.lang.c Subject: Re: if (p), where p is a pointer - PLEASE READ Message-ID: <693@sfmag.UUCP> Date: Fri, 13-Sep-85 07:53:29 EDT Article-I.D.: sfmag.693 Posted: Fri Sep 13 07:53:29 1985 Date-Received: Sat, 14-Sep-85 06:18:24 EDT References: <118@mit-hector.UUCP> <2792@sun.uucp> Organization: AT&T Information Systems, Summit, NJ Lines: 55 > > An C idiom I see (and write) frequently is > > > > if (ptr) > > > > Will this work correctly on a machine where NULL is not 0? Does it really > > need to say > > > > if (ptr != NULL) > > 1) "if (X)" means exactly the same thing as "if (X == 0)", for all X > (assuming "if (X == 0)" has a meaning in the first place, i.e. if X is a > struct, forget it). No! "if (X)" means exactly the same thing as "if (X != 0)"! > 2) NULL is #defined to be 0, so "if (ptr == NULL)" is equivalent to "if (ptr > == 0)". No again! Null is defined to be "some flavor of 0", and "if (ptr == NULL)" is almost always equivalent to "if (ptr == 0)". I have seen NULL defined as an integral constant and as "(char *) 0", with equivalent results in all available implementations. > So both statements are equivalent. The compiler is capable of realizing > that the LHS of the comparison is a pointer and the RHS is the constant 0, > and generates code to compare the pointer to a null pointer of the > appropriate type. The only place where the compiler can't recognize that a > constant 0 is really a null pointer of the appropriate type is in a function > call (i.e., "setbuf(stream, 0)" and "setbuf(stream, NULL)" are wrong; you > have to say "setbuf(stream, (char *)0)" or "setbuf(stream, (char *)NULL)"). It is for this reason that NULL is often defined as "(char *) 0" (often, there is an enclosing pair of parentheses in the definition). > ANSI C will permit you to say something like > > void setbuf(FILE *, char *); > > in , in which case the compiler knows that the "0" in "setbuf(0)" > is to be converted to "(char *)0" and will do it for you. Yes, this and the related features of ANSI C are "*good* things". > Guy Harris Tiny flame: I am usually loathe to include an article in its entirety, but Guy is one of the few posters who (often) constrains his articles to only the facts of the matter at hand, without "religious" flames (at least in non-"religious" newsgroups). That he goofed here is most likely due to fingers running on auto-pilot with a noisy signal.... -- Marty Shannon UUCP: ihnp4!attunix!mjs Phone: +1 (201) 522 6063 Disclaimer: I speak for no one.