NOT Educating FORTRAN programmers to use C

Jim Giles jlg at lambda.UUCP
Tue Jan 23 12:15:41 AEST 1990


>From article <7536 at chaph.usc.edu>, by jeenglis at alcor.usc.edu (Joe English):
> [...]
>     src = str2;
>     while (*src && remaining)  {
>         *dst++ = *src++;
>         remaining--;
>     }

Terribly innefficient.  It relies on your compiler being _really_ clever
about optimizing.  A _VERY_ good C compiler _might_ make the above loop
into a block move instruction.  It would still have to prescan the string
to find out how long the block move should be.  Assuming (in addition to
all the miracles so far) that the compiler does prescanning with a single
instruction also (block scan), the time for this is roughly twice what the
equivalent Fortran code would use.

I don't know why you didn't use strlen() followed by memcpy().  This would
do exactly the optimizations (plus or minus a couple of function calls)
that most C compilers would otherwise miss.  Assuming that ANSI compatible
C compilers are close on the horizon, I would bet that memcpy() and
strlen() would be "inlined" by most compilers.

Indeed, for your whole example (which had two loops as above), I don't
see why you didn't use strcpy() followed by strcat().  This would assume
that the two library functions were efficiently implemented (these two
are usually written in assembly).  Using these, you still have to pay
for the prescanning of the input strings, but you would pay less for
procedure call overhead.

Finally, if you had not used gets() to get the original strings, but
had used something which returned the length explicitly, you could
have used memcpy() only!  This would _FINALLY_ be as efficient as
Fortran concatenation (plus or minus the procedure call - Fortran
is _MORE_ likely to inline, at least until ANSI C compilers are
widely available).

Still, it doesn't look as good.  In Fortran, concatenation is
simply:
      STRING3 = STRING1 // STRING2

Much more legible IMHO.

J. Giles



More information about the Comp.lang.c mailing list