Re^2: Another silly question

Niels J|rgen Kruse njk at freja.diku.dk
Fri Apr 28 07:17:09 AEST 1989


cik at l.cc.purdue.edu (Herman Rubin) writes:

>Now suppose I am doing some serious array operations, and I have to know
                             ?????????????
>whether one array buffer is longer than another.  The elements are of type
             ????????????
Sounds like you are doing fortran style memory management with
one big monster array parceled out. You don't *have* to do that
in C, you know.

>long.  Do I have to do this multiplying and dividing by 4 all the time?

No. If you have pointers

long *p1,*p2,*p3,*p4;

with p1 <= p2 and p3 <= p4 and want to test (p2-p1) < (p4-p3),
you can write

if ((char *)p2 - (char *)p1 < (char *)p4 - (char *)p3)

which won't generate any shifting.

If the architecture in question allows longs that are not
aligned on a natural byte boundary, this is not equivalent to
the test without the casts, so the compiler can not be blamed
for not doing this optimization itself.
Another case for RISC :-)
This hand optimization doesn't hurt you on word addressed
machines, as they generaly require longs aligned on a word
boundary. Hence
if ((char *)p2 - (char *)p1 < (char *)p4 - (char *)p3)
is equivalent to
if ((int *)p2 - (int *)p1 < (int *)p4 - (int *)p3)
and that optimization can be expected from the compiler.

>Another example of "user-friendly" which turns out to be "user-inimical."
>--
>Herman Rubin, Dept. of Statistics, Purdue Univ., West Lafayette IN47907
>Phone: (317)494-6054
>hrubin at l.cc.purdue.edu (Internet, bitnet, UUCP)
-- 
         Niels J|rgen Kruse
Email    njk at diku.dk
Mail     Tustrupvej 7, 2 tv, 2720 Vanlose, Denmark



More information about the Comp.lang.c mailing list