[LUAU] Re: Python (Was Re: Hosef)

Jim Thompson jim at netgate.com
Wed Nov 23 10:24:23 PST 2005


Tim Newsham wrote:

>>>     for ( ; *s++ = *t++ ; )         ;
>>
>>
>>                   while (*s++ = *t++) {
>>                           /* empty body */
>>                     } ;.
>
>
> I always found "continue" to be a lot more explicit in situations
> like this:
>
>      while(*s++ = *t++)
>          continue;
>
> the empty semi-colon being the least attractive alternative (did
> he really mean to leave the body empty?  not to mention the greener
> programmer will easily overlook the semicolon).

I learned a long time ago to always include the curly braces, since it 
makes it easy to
insert additional code without the comma-hack.   (Once the braces are 
in, its easy to
delete code as well.)

Back when we all worked on 80x24 CRT vt100 clones, getting the function 
good and dense was a fine thing.
(Make the function fit on a page, son... that way you can see all of 
it.)  Now that bigger windows are the norm,
it doesn't make any sense at all.

>> In any case, both examples have the issues of the side-effects of the 
>> assignment (being used for the test here).  The author of either 
>> example also has to worry about the loop terminating (finding a null 
>> pointer).
>
> No complaints about assignment in the loop test? :)
> (Another sure way to confuse the younger C coder).

yeah, I called that out "side-effects of the assignment (being used for 
the test here)"

while (*t) {
    *s++ = *t++;
}

which compiles to the nearly the same code as both versions of the 
'while' loop and the 'for' loop and probably takes the same number of 
clocks, at least on a x86 box.

>> For all but trivial copies like this memcpy() (aka bcopy()) is 
>> probably a better "solution", though of course it won't terminate on 
>> a null pointer like the above.
>
>
> But strcpy() will :)

Only if you're assuming s and t are char *.   Of course, if they are, 
then, unless s or t is unaligned on a long boundary, strcpy is likely to 
be quite a bit faster than the simple loop, since it copies either 4 
bytes (on 32 bit machines) or 8 bytes (on 64 bit machines) at a time, 
and employs a bit mask test to see if any of the chars in the 
word-to-be-copied are null, falling back to the simple 
copy-a-char-at-a-time as necessary.

I suppose there's memccpy(), but that also requires knowing the maximum 
length of the source array
(And dest array if you want to play safe.)  

Of course, if you know the length, you can use Duff's device:
http://www.lysator.liu.se/c/duffs-device.html

jim




More information about the LUAU mailing list