ANSI C

Guy Harris guy at sun.uucp
Thu Aug 14 15:44:49 AEST 1986


> In 3.2.2.3, "(void *)0" is called a null pointer constant, though 5.6.3.12
> says the value of NULL is implementation-defined.  I take this to mean that
> the internal representation of (void *)0 need not have all bits clear.

Yes.  I'm certain there are many machines out there that either have C
implementations or should have them that have a representation for null
pointers that is not a bucket of zero bits.

> The constant 0 used in a pointer context still denotes the null pointer,
> but an integer variable whose value happens to be zero need not produce
> the null pointer when cast.

Yes.  This may be considered questionable, since, given the declarations

	int i;
	char *p;

the statements

	i = 1; p = i;

and

	p = 1;

should be expected to stuff the same value into "p", but the statements

	i = 0; p = i;

and

	p = 0;

need not stuff the same value into "p" - i.e., the constant expression 0 is
treated differently when converting to a pointer type than any other
integral expression.  Unfortunately, there's not a hell of a lot you can do
about it.  If C had a keyword "nil" that would, when it appears in an
expression, be converted to a null pointer of the appropriate type (as the
constant expression 0 is converted now), this problem wouldn't occur;
however, it's a little to late to fix this now, given all the code out there
that uses 0 for this.

"Fixing" it the other way, by having any integral expression with the value
0 convert to a null pointer, would 1) add some extra inefficiency to
integer-to-pointer conversions on machines with special null pointer
representations without much benefit (if any), and 2) surprise some code
that does want to grab a pointer value, fiddle the bits (setting a ring
number, for instance) and then stuff the value back into the pointer, if a
pointer value of all zero bits is a valid pointer.

> Also, if I have a pointer variable whose value happens to be NULL and I
> cast it into int, I'll likely get the internal form (what I'd get if I
> used a union) rather than zero as a result, right?

Right.

> In boolean context ("if (p)"), there is an implied comparison with NULL,
> not an implied cast to int.

Actually, it's an implied comparison with 0; however, the 0 has to get
converted to the type of "p", so that the effect is the same as
"if (p == 0)", namely that "p" gets compared with a null pointer.
-- 
	Guy Harris
	{ihnp4, decvax, seismo, decwrl, ...}!sun!guy
	guy at sun.com (or guy at sun.arpa)



More information about the Comp.lang.c mailing list