if(p)

Jeff Kresch jak at adelie.UUCP
Sat Oct 19 04:21:33 AEST 1985


> Re: Marv Rubenstein's message.
> 
> int i;
> foo *p;
> 
> 	i=0;
> 	if(p==i)...
> 
> What's wrong with this? It's identical to "if(p==(foo *)i)" according to the
> default expression evaluation rules. Any special meaning of 0 should be
> handled in the evaluation of (foo *)i.

We seem to be going around in circles with this one.

First, it is stated clearly in K&R that the only integer that may be
compared with a pointer is the *constant* zero.  (foo *)i is not a
constant.  Any other comparisons between integers and pointers is
machine dependent, regardless of whether the integer is casted correctly
or not.  

The reasons for this rule are not hard to understand from the point of
view of implementing a compiler producing efficient code.  Checking for
the constant zero can be done at compile-time.  The compiler just has to
substitute a different value if one is required.  Checking for a
variable containing the value zero would require that the compiler put
in extra code to do this at run time.  This *code* (not the compiler)
would have to check the value of the variable, and if it was zero,
substitute the proper null value in the comparison, if need be.

Looking at it from this perspective, it is easy to see why 

        if (p)

is reasonable.  This is always taken to mean

        if (p != 0)

and can be detected at compile-time.  The compiler can substitute the
appropriate value if it is required.



                                                They call me
                                                JAK



More information about the Comp.lang.c mailing list