Explanation, please!

Doug Gwyn gwyn at smoke.ARPA
Sun Aug 28 15:19:01 AEST 1988


In article <dpmuY#2EBC4R=eric at snark.UUCP> eric at snark.UUCP (Eric S. Raymond) writes:
>Dollars to doughnuts this code was written on a RISC machine.

Send me my doughnuts!  (Or dollars, if you prefer.)  RISC machines
were practically non-existent when this C code was first written down
(whether or not by Tom Duff, I'm not sure).  It probably appeared on
a PDP-11, perhaps a VAX.

I suspect the first use of Duff's device was as an "efficiency hack",
but as you observe it is not universally the most efficient method.

The modern VALID reason for such code is that it is a relatively
efficient way to do something portably that CANNOT BE DONE by
using the "preferred block copy routine" supplied by an implementation
(be it bcopy() or memcpy()).  Whenever the preferred routine will
work correctly (in the portable case, that means whenever the source
and destination fields do not overlap), then of course one should use
it, especially since if the C vendors are doing their job, the C
library routine (which could also be expanded in-line by the compiler)
will be near-optimally tuned for each specific architecture.

P.S.  Some implementations of bcopy() and memcpy() do guarantee
proper handling of overlapping fields.  But not all do, so one cannot
count on it if one's trying to write truly portable code.  ANSI C will
specify a new function memmove() with this property guaranteed.



More information about the Comp.lang.c mailing list