[net.micro.68k] comparing pointers to integers

topher@cyb-eng.UUCP (Topher Eliot) (05/13/85)

>Of course, you can do something like:

> >long *longptr;
> >long templong;
> >main()
> >{
> >    templong = longptr;
> >    if (templong == 32) ; /* do something nerdy */
> >}
> 
> I recommend using one of the two constructs
> 
>     ( longptr == (long *)32 )
> or  ( (int)longptr == 32 )
> 
> which are guaranteed to do what you want (the cast is equivalent to assigning
> to a temporary of the right type, and the assignment is defined as "with no
> conversion").  Note that the second case is equivalent to your workaround of
> "templong = longptr; if( templong == 32);", but without the extra assignment.

I, too, recommend using one of the two casts mentioned.  However, I think
that both authors have misinterpreted K&R when they suggest assigning a
pointer value into an integer without explicitly casting it to integer
type.  Admittedly, on P.42, the book says "The precise meaning of a cast is
in fact as if expression were assigned to a variable of the specified type,
which is then used in place of the whole construction."  However, it does
NOT say that you can casually assign any type to any type -- obviously,
assigning an integer value to a 20-byte structure isn't allowed, but they
don't explicitly forbid it HERE.  Also, in the discussion leading up to this
quote, on P.41, they give a whole list of conversion rules about chars,
ints, unsigneds, floats, and doubles, finally ending with "Otherwise the
operands must be int, and the result is int."  Pointers are not mentioned
among the allowed conversions.

In addition, in Appendix A, PP 7.14 (Assignment operators, P. 191), all
sorts of assignment operators are discussed (= += -= etc).  They then say
"In += and -=, the left operand may be a pointer . . .", and say nothing
about allowing this with normal assignment.  They then go on to say
"The compilers CURRENTLY allow a pointer to be assigned to an integer, an
integer to a pointer . . . This usage is nonportable . . ." (emphasis
mine).

Bottom line:  I have bumped into at least one compiler that would complain
about mis-matched types if I tried to assign a pointer variable to an
integer variable or vice versa without explicitly casting.  I think it was
right in doing so.  Usually I had forgotten a * or &.  Only rarely did I
really want the conversion.

Cheers,
Topher Eliot                                           Cyb Systems, Austin, TX
         {gatech,ihnp4,nbires,seismo,ucb-vax}!ut-sally!cyb-eng!topher