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

Guy Harris guy at sun.uucp
Mon Sep 16 08:57:34 AEST 1985


> No!  "if (X)" means exactly the same thing as "if (X != 0)"!

Sorry, I slipped - 1/2 typeo, 1/2 mindo.

> > 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.

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).

#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.

	Guy Harris



More information about the Comp.lang.c mailing list