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

M.J.Shannon mjs at sfmag.UUCP
Tue Sep 17 17:06:24 AEST 1985


> > > 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.
> 
> No!  If NULL is defined as 0, and "p" is an "int *",
> 
> 	if (p == NULL)	/* or != NULL */
> 
> generates correct code and no messages.  If NULL is defined as "(char *)0",
> it probably generates correct code (the compiler should know enough to
> coerce the "(char *)0" into an "(int *)0", just as it should know enough to
> coerce "0" by itself into "(int *)0", *but* it also generates the warning
> 
> 	illegal pointer combination
> 
> at least on PCC-based compilers.

True and proper.  I overstated reality above.

> And in the case
> 
> 	foo(p)
> 	int *p;
> 	{
> 		...
> 	}
> 
> 	bar()
> 	{
> 		...
> 		foo(NULL);
> 		...
> 	}
> 
> unless "(char *)0" and "(int *)0", as function arguments, cause the exact
> same bit pattern to be passed, #defining NULL as "(char *)0" will not cause
> correct code to be generated (unless you have an ANSI C compiler and have
> declared "foo" as taking a "int *" as an argument - but if you have such a
> compiler and have so declared "foo", #defining NULL as 0 will also cause
> correct code to be generated).

Well, now we come to the can of worms which causes some implementations to
#define NULL (char *) 0: machines where pointers occupy more space than ints.
In these implementations, foo(NULL) is absolutely incorrect (duplicate paren'd
comment from previous paragraph) (and try porting "typical" code to such
machines; but I digress).

> #defining NULL as *anything* other than 0 is incorrect!  The trouble with
> that declaration is that it looks like it solves the problem when it really
> doesn't.

Same comment as above.  The solution may be that NULL should be 0L (but what
about the venerable old PDP-11?  In that case, foo(NULL) passes too much stuff
on the stack.  So, what is *the* answer?)....

> 	Guy Harris
-- 
	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