if (p), where p is a pointer (REAL portability)

Guy Harris guy at sun.uucp
Fri Sep 20 14:37:25 AEST 1985


> NULL *IS* defined as (char *)0

The meaning of the above statement, presumably, is "there is no place where
NULL is defined as anything other than (char *)0.

Well:

4.2BSD's /usr/include/stdio.h:
 ...
#define	NULL	0

System V Release 2's "/usr/include/stdio.h":
 ...
#define NULL		0

Sun UNIX 2.0's "/usr/include/stdio.h":
 ...
#define	NULL	0

Need I go on?  One counterexample is sufficient to show that the above
statement is false.

> and SHOULD only be used in comparisons with character pointers!

> 	if ((fp = fopen(file, "r")) == NULL)		/* NOT QUITE CORRECT */

> 	if ((fp = fopen(file, "r")) == (FILE *)0)	/* BETTER */

If NULL were defined as (char *)0, the first comparison would be incorrect.
However, it isn't, so it is correct.  Furthermore,

	if ((fp = fopen(file, "r")) == 0)

is just as good.  The C compiler is quite capable of realizing that since
the LHS of the "==" has type "FILE *", the RHS has to be coerced to the same
type.

There are few things more tiresome than reading debates over whether 2+2 is
5 or 7.  If anybody still thinks that

	1) NULL is always #defined as (char *)0

	2) NULL should be defined as an integer with the same bit pattern
	   as a null pointer on the machine in question

	3) 0's have to be cast to an appropriate pointer type in
	   contexts where the compiler can automatically do the
	   coercion

would they please go back and read K&R or Harbison and Steele until they no
longer think so?

	Guy Harris



More information about the Comp.lang.c mailing list