Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!mouse From: mouse@thunder.mcrcim.mcgill.edu (der Mouse) Newsgroups: comp.lang.c Subject: Re: Increment Counters in declaration or in loop? (style question) Message-ID: <1991Jun15.154420.25405@thunder.mcrcim.mcgill.edu> Date: 15 Jun 91 15:44:20 GMT References: Organization: McGill Research Centre for Intelligent Machines Lines: 49 In article , dm@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@larry.mcrcim.mcgill.edu