Should I convert FORTRAN code to C?
kenny at p.cs.uiuc.edu
kenny at p.cs.uiuc.edu
Thu Jul 7 11:10:00 AEST 1988
In an article written yesterday, I present:
PROGRAM 7.
>[main program still hasn't changed]
>grdgen (df, nlev)
> register int df; /* no. of degrees of freedom */
> register int nlev; /* no. of levels each df */
>{
> register int i;
> register int j;
> register int totaldfm1 = df - 1;
> static int value [MAXDF]; /* to hold current values of all df's */
>
> for (;;) {
> while (df >= 0) { /* Set up initial values */
> i = 0;
> value [df--] = i;
> }
>
> for (j = 0; j < totaldfm1; ++j) /* Print a node */
> printf ("%d ", value [j]);
> printf ("%d\n", value [j]);
>
> for (;;) { /* Develop another node */
> if (df >= totaldfm1) return;
> i = value [++df] + 1;
> if (i < nlev) {
> value [df--] = i;
> break;
> }
> }
> }
>}
And I don't know what posessed me. The program can be simplified
quite a bit. One of the assignments to i is useless, and a `break'
statement can be drawn out of a loop. While no version is truly
final, I'd prefer the following:
PROGRAM 7A.
[main program still hasn't changed]
grdgen (df, nlev)
register int df; /* no. of degrees of freedom */
register int nlev; /* no. of levels each df */
{
register int i;
register int j;
register int totaldfm1 = df - 1;
static int value [MAXDF]; /* to hold current values of all df's */
for (;;) {
while (df >= 0) /* Set up initial values */
value [df--] = 0;
for (j = 0; j < totaldfm1; ++j) /* Print a node */
printf ("%d ", value [j]);
printf ("%d\n", value [j]);
do { /* Develop another node */
if (df >= totaldfm1) return;
i = value [++df] + 1;
} while (i >= nlev);
value [df--] = i;
}
}
BTW, the program analysis techniques that I've been promulgating *do*
come up with this fragment; I was just careless running them by hand
(The fact that they *can* be automated doesn't mean that they *have*
been automated).
The more I look at this version, the more I like it. The loop breaks
down into three steps: initialize, print a node, increment some index.
It's particularly satisfying that a series of essentially mechanical
steps was able to derive an iterative version as clean as this from
the original recursive version. I doubt I'd have done as well setting
out to write an iterative version by hand.
More information about the Comp.lang.c
mailing list