use of if (!cptr) and if (cptr), where cptr is a *

Chris Torek chris at mimsy.UUCP
Thu Jul 20 00:53:27 AEST 1989


In article <10100 at mpx2.mpx.com> erik at mpx2.mpx.com (Erik Murrey) writes:
>... what happens when sizeof(int) != sizeof(char *)?

It makes no difference, if the compiler works.

>Suppose a char * is 6 bytes, and an int is 4.  Suppose the upper 2 bytes
>are used as some sort of descriptor.  Now suppose malloc() returns
>a new memory block which just happens to be at the beginning of a new
>page, and our char * looks like:
>
>NN NN 00 00 00 00
>
>(NNNN is our descriptor).
>
>Now, what happens with:
>
>if (cptr == 0) ?  Does the compiler cast the cptr to an int, and loose
>the descriptor?  (And tell is that it is null?)

The comparison compiles into

	compare <register or memory holding cptr> against
		<canonical value for (char *)0>

That is, if a nil pointer of type `pointer to char' happens to
be represented by a descriptor value of 65535, it compares the
descriptor field (NN NN) against 0xffff.  If a nil pointer to
char happens to be represented by six zero bytes, it compares
all six bytes against zero.

>How about:
>
>if (!cptr) ?

`if (!cptr)' *means* `if (cptr == 0)', by the language definition;
the compiler emits the same code sequence, or at least a code sequence
that accomplishes the same thing, or else the compiler is broken.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list