Increment Counters in declaration or in loop? (style question)

Garrett Wollman wollman at emily.uvm.edu
Fri Jun 14 13:45:27 AEST 1991


[The original poster asks about style wrt
	for(init; cond; index++) {
		some_other_var++; other_stuff();
	}

versus
	for(init; cond; index++,some_other_var++) {
		other_stuff();
]

In general, I think that there are two types of situations here.  For
example, I might find myself doing something like:

	for(i=0,j=0; i<imax && i<jmax; i++)
		if(a[i] > 0)
			b[j++] = a[i];

where clearly, the increment of j cannot be done within the context of
the for itself, because it is conditional.  However, in many cases,
this is not true.  Generally, these fall into two categories:  either
the programmer is trying to hand-optimize the code, or the programmer
is trying to express what stylistically ought to be a while loop as a
for loop instead.

I do not understand why people do that.  Perhaps it makes dealing with
certain brain-damaged debuggers easier to have

	for(init; cond; action1,action2,action3);

than

	init;
	while(cond) {
		action1;
		action2;
		action3;
	}

It's a good obfuscatory technique, but I don't think anyone would
disagree with me when I say that the latter is stylistically much better.

The other case, that of hand-optimization, is somewhat more difficult.
I know that all of the compilers I use can do a much better job of
strength-reduction, loop unrolling, CSE, constant code motion, and all
the rest, than I can.  So in general, instead of doing something like
the originally proposed

	for(i=0; i < imax; i++)
		printf("%d: %c\n",i,str++);

I would instead almost always prefer

	for(i=0; i < imax; i++)
		printf("%d: %c\n",i,str[i]);

since I am certain that *if* the second form were more efficient than
the first *on my specific target machine*, then the compiler would
do the conversion automatically, and probably allocate a register for
the temporary copy of str as well, not to mention other potential
optimizations.  I would be surprised if GCC doesn't do this under -O
-fstrength-reduce [and a bunch of other -f's all of which IMHO should
be enabled by -O automatically], at least for some values of 'target
machine'.  

And, in fact, I find that it does just that (when I substitute a
pointer type which is non-trivial) on the NS32532 in this MultiMax;
MIPS CC on the SGI 4D/240S does exactly the same thing (comparing -O0
with -O2).

So that's my opinion.  Perhaps Dan Bernstein will disagree.

-GAWollman
Garrett A. Wollman - wollman at emily.uvm.edu

Disclaimer:  I'm not even sure this represents *my* opinion, never
mind UVM's, EMBA's, EMBA-CF's, or indeed anyone else's.



More information about the Comp.lang.c mailing list