if (p), where p is a pointer - PLEASE READ

M.J.Shannon mjs at sfmag.UUCP
Fri Sep 13 21:53:29 AEST 1985


> > 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 <stdio.h>, 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.



More information about the Comp.lang.c mailing list