Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!husc6!necntc!ima!haddock!karl From: karl@haddock.UUCP (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: Copying a constant number of bytes Message-ID: <563@haddock.UUCP> Date: Mon, 15-Jun-87 17:15:15 EDT Article-I.D.: haddock.563 Posted: Mon Jun 15 17:15:15 1987 Date-Received: Sun, 21-Jun-87 02:50:25 EDT References: <900@bloom-beacon.MIT.EDU> Reply-To: karl@haddock.ISC.COM.UUCP (Karl Heuer) Distribution: world Organization: Interactive Systems, Boston Lines: 32 In article <900@bloom-beacon.MIT.EDU> newman@athena.mit.edu (Ron Newman) writes: >[To copy a constant number of bytes one can use bcopy/memcpy, or] > struct nbytes {char s[NBYTES];}; > *(struct nbytes *)b = *(struct nbytes *)a; >... But can I count on a compiler generating efficient code for method (2)? Well, you can't count on a compiler generating efficient code for ANYTHING, but the compiler will almost certainly use something at least as efficient (timewise) as the bcopy/memcpy subroutine. (Usually it's better, since the compiler knows the exact size, whereas the subroutine has to handle the general case.) Unfortunately, being efficient isn't as important as being right. The major problem is that the pointers a and b, since they are not really of this struct type, may not have the correct alignment. In particular, I seem to recall the SVR2 compiler for the 3B2 would force a stricter-than-necessary alignment (and hence size) on all structs. Thus, you might even get more bytes than you asked for. >Is the answer any different if I know that "a" and "b" are 32-bit aligned, or >that NBYTES is a multiple of 4? The answer to your original question is "No", unless the compiler knows it too. (It does know the value of NBYTES, but probably doesn't know the alignment of the pointers.) The answer I gave is still correct (it's not strictly portable), but if the size and alignment are sufficiently large you happen to get the right answer on the machines I'm familiar with. My recommendation is to use memcpy. If you choose not to, I suggest that the resulting code should be well-commented. Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint