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

der Mouse mouse at thunder.mcrcim.mcgill.edu
Sun Jun 16 01:44:20 AEST 1991


In article <XamD43w164w at phsbbs.princeton.nj.us>, dm at phsbbs.princeton.nj.us (Doron Meyer) writes:

> What is the 'preferred' stylistic method of incrementing counters?
> For example, this simple for loop.

> for (count=0; count<4; count++)
> {
>   printf("name[%d]: %c\n", count, ptr++);

> In this instance, the loop counter is incremented in the declaration
> of the for loop, and the ptr variable, which still gets incremented
> each time the loop cycles, is incremented within the body of the
> loop.

> Is this more of a matter of personal opinion than anything else?

Ummm...it's certainly partly pure style.

One possible semantic difference occurs when some increments should
always happen.  This is obvious when they're within if statements or
some such, but it may be less obvious when they're skipped due to a
continue statement.  In the rest of this I assume conditions are such
that there's no semantic difference.

I would say that the side-effect (increment, decrement, function call,
etc) belongs in the for only when it is conceptually part of the loop
control.  For example,

for (pa=a,pb=b;*pa!=*pb;pa++,pb++)

is fine, where the loop is conceptually moving two pointers in
parallel.  But 

count = 0;
for (consp=list;consp;consp=consp->cdr)
	{ count ++; frob_it(consp); }

is certainly to be preferred (preferably spaced out more) over

for (consp=list,count=0;consp;consp=consp->cdr,count++,frob_it(consp)) ;

The line I'm trying to describe here is fuzzy, I'll agree; that's why I
say it's partly personal style.

					der Mouse

			old: mcgill-vision!mouse
			new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list