Question of Ignorance

Morris M. Keesan keesan at bbncca.ARPA
Sat May 11 00:20:30 AEST 1985


------------------------------
>    Pardon my excess stupididy, but I have a question about the
>** CORRECT ** way a C-compiler (by definition) should handle the
>following program. Consider main.c, below
>long *longptr;
>main()
>{
>if(longptr== 32) ;
>}
 . . . code examples . . .
>    Note that the Alcyon compiler leaves the constant alone if the
>thing is a char; shifts it left one if it is an int (2 bytes), and
>left two if it is a long (4 bytes).
>
>     Bill Allen at Alcyon Corporation assures me that this is not
>a bug, that constants MUST BE MULTIPLIED BY THE NUMBER OF BYTES
>when doing a test with a pointer. He even swears that the regular
>C compiler cc must do this.
>
>Of course, you can do something like:

>long *longptr;
>long templong;
>main()
>{
>    templong = longptr;
>    if (templong == 32) ; /* do something nerdy */
>}
>
>David Anthony
>Senior Analog Nut
>DataSpan, Inc.
---------------------
    From The C Reference Manual, section "7.7 Equality Operators" (page 190 of
K&R): "A pointer may be compared to an integer, but the result is machine
dependent unless the integer is the constant 0."  This means that by definition
a C compiler is free to do what it wants in this case.  Personally, I think that
Alcyon is confused, but their compiler is behaving in a legal way.  My guess
is that it's easiest for them to treat all operations between pointers and
integers the same way, and so they do the same scaling for + and ==.
    Because of the undefined behaviour of ptr == int, and because some newer C
compilers don't allow the operation at all (my latest draft copy of the ANSI 
standard doesn't allow it), 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.
-- 
Morris M. Keesan
{decvax,linus,ihnp4,wanginst,wjh12,ima}!bbncca!keesan
keesan @ BBN-UNIX.ARPA



More information about the Comp.lang.c mailing list