Pointer arithmetic and comparisons.

Karl Heuer karl at haddock.ima.isc.com
Thu Dec 14 08:41:35 AEST 1989


In article <2908 at murtoa.cs.mu.oz.au> rob at murtoa.UUCP (Robert Wallen) writes:
>Although K&R sez that you should be able to do p < q where p and q point to
>members of the same array, Turbo C hangs an extra requirement on you.  That
>is, that the pointers are normallized as well.

If the pointers point into the same array, which is smaller than 64K, why
shouldn't they already be normalized?

>Now a beef.  Why check for (p <= pend)?  Why not just (p == pend) ?

I believe this one is in The Elements of Programming Style.  To roughly
paraphrase from memory (it's been a decade since I read it): when either of
two comparisons is correct (because the case where they differ "can't
happen"), it's considered better to use the one that would stop the loop in
the event that the "impossible" happens.

Also, in a segmented implementation (p == q) is generally slower.  For
equality compares, the compiler has to ensure that the pointers are
normalized, but with non-huge use of (p < q) it can assume that the pointers
will already be in the same segment.

Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list