Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84 SMI; site sun.uucp Path: utzoo!watmath!clyde!burl!ulysses!ucbvax!decvax!decwrl!sun!guy From: guy@sun.uucp (Guy Harris) Newsgroups: net.lang.c Subject: Re: if (p), where p is a pointer - PLEASE READ Message-ID: <2792@sun.uucp> Date: Thu, 12-Sep-85 05:06:22 EDT Article-I.D.: sun.2792 Posted: Thu Sep 12 05:06:22 1985 Date-Received: Sat, 14-Sep-85 05:16:10 EDT References: <118@mit-hector.UUCP> Organization: Sun Microsystems, Inc. Lines: 32 > 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). 2) NULL is #defined to be 0, so "if (ptr == NULL)" is equivalent to "if (ptr == 0)". 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)"). 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. Guy Harris