Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Alternatives to modifying loop var in the loop.

Reply
Thread Tools

Alternatives to modifying loop var in the loop.

 
 
Phil Carmody
Guest
Posts: n/a
 
      12-29-2013
James Kuyper <(E-Mail Removed)> writes:
> On 12/27/2013 02:14 AM, Matt wrote:
> > I'm sure I've read somewhere that it's considered bad practice to modify
> > the value of the variable on the right of a comparison operator inside
> > the loop concerned.

>
> The validity of that guideline depends upon what you're doing. For
> instance, if a loop starts with
>
> for(int item=0; item < item_count; item++)
>
> then it is potentially very confusing to change either item or
> item_count within the loop. That doesn't mean you shouldn't do it - if
> there's sufficiently good reason so do so, then you should; but you
> should draw attention to the lines where you perform the modification by
> inserting comments.


Sometimes even variable names can be enough of a clue, but yes, that
single line is enough of an idiom that it carries a lot of baggage about
what one would expect to follow.

> On the other hand, I've written code to do a bracketed binary search of
> a sorted array like the following:
>
> while(low < high)
> {
> int mid = (low+high)/2;
> if(array[mid] < x)
> low = mid+1;
> else
> high = mid;
> }
>
> The fact that this code modifies both "low" and "high" inside the loop
> is not a problem, because it's very clear why and how it's modifying them.


I notice that one example was a for() and the other was a while().
I'm a great believer that people over-use for() - I hate seeing ``; )'',
for example. That immediately says "should have been implemented as a
while loop" to me. My expectations are different from the two constructs
certainly.

Phil
--
The list of trusted root authorities in your browser included the
United Arab Emirates-based Etisalat, which was caught secretly
uploading spyware onto 100,000 customers' BlackBerries.
http://www.wired.com/threatlevel/200...ckberry-spies/
 
Reply With Quote
 
 
 
 
Phil Carmody
Guest
Posts: n/a
 
      12-29-2013
Dr Nick <(E-Mail Removed)> writes:
> Ben Bacarisse <(E-Mail Removed)> writes:
>
> > Matt <(E-Mail Removed)> writes:
> >
> >> On 28/12/13 20:19, Ben Bacarisse wrote:
> >>> you have a redundant loop in
> >>> getscore which is the time-limiting function right now. You can count
> >>> the matching colours without looping over colours.
> >>
> >> http://code.mattsmith.org.nz/masterm...ew_get_score.c
> >>
> >> I still iterated through colors once to set some stuff to 0.

> >
> > You can use '= {0};' as the initialiser to zero the arrays.

>
> I've not checked to see if it's still the case, but one of the most
> irritating features of GCC that I've come across is that it warns that
> this is not a complete initiator.
>
> Now if I've done = {1,2,3,4,5,6} for a 7 element array, I may well not
> want the last initialised to 0, so I can understand the warning. But =
> {0} should be a special case.


If we're hypothesising, then why not have the default zero initialiser
syntax be = {}; ? 2 initialisers is some. 1 initialiser is some. 0
initialisers is none. If isolating a special case, surely the one that
stands on its own (none, vs. some) is the best one to choose?

> Of course, you can always turn off warnings etc, but this particular one
> seemed especially irritating.


I have a few "favourites" which I like less.
Phil
--
The list of trusted root authorities in your browser included the
United Arab Emirates-based Etisalat, which was caught secretly
uploading spyware onto 100,000 customers' BlackBerries.
http://www.wired.com/threatlevel/200...ckberry-spies/
 
Reply With Quote
 
 
 
 
Seebs
Guest
Posts: n/a
 
      12-29-2013
On 2013-12-29, Eric Sosman <(E-Mail Removed)> wrote:
> I think that "elegance" means different things to the two
> of us (eye of the beholder, again). The quality you describe
> as "elegance" is something I'd prefer to call "clarity," and I
> agree that it's a desirable attribute regardless of whether you
> call it clarigance or eleganity.


Hmm. You may have a point.

> ... and that's why I don't think "elegance" is a useful
> criterion: If you can't measure it, you can't tell whether it's
> present or absent, or to what degree.


I'm not sure that's right. Or rather: Even if things are subjective,
they may still be useful criteria. They may be observer-variant, but I
would tend to consider "pleasant to work on" a significant trait to
consider when evaluating prospective projects.

>[*] IIRC, Weinberg reported on a similar experiment in "The
> Psychology of Computer Programming." Groups of computer science
> students read the same piece of code, either in its original form
> or with the comments removed. The students who saw the UNcommented
> code found and fixed more of its errors than those who had the
> "benefit" of the commentary ...


That's not surprising. Comments that tell you what's supposed to happen
are likely to make you expect that to be what happens.

I usually aim comments at explaining why I do something unexpected
that took a while to figure out. Otherwise, code is usually pretty
comprehensible if it's reasonably clear.

-s
--
Copyright 2013, all wrongs reversed. Peter Seebach / http://www.velocityreviews.com/forums/(E-Mail Removed)
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
Autism Speaks does not speak for me. http://autisticadvocacy.org/
I am not speaking for my employer, although they do rent some of my opinions.
 
Reply With Quote
 
Kenny McCormack
Guest
Posts: n/a
 
      12-30-2013
In article <l9pebv$s9s$(E-Mail Removed)>,
Eric Sosman <(E-Mail Removed)> wrote:
....
> I think that "elegance" means different things to the two
>of us (eye of the beholder, again). The quality you describe
>as "elegance" is something I'd prefer to call "clarity," and I
>agree that it's a desirable attribute regardless of whether you
>call it clarigance or eleganity.


Interestingly enough, the actual, original definition of "elegant" is
"minimalist". Which, in the context of the religion of CLC, ends up
meaning exactly the opposite of "clarity" (since "clarity" usually ends up
meaning "be as verbose as possible").

--
The problem in US politics today is that it is no longer a Right/Left
thing, or a Conservative/Liberal thing, or even a Republican/Democrat
thing, but rather an Insane/not-Insane thing.

(And no, there's no way you can spin this into any confusion about
who's who...)
 
Reply With Quote
 
Aleksandar Kuktin
Guest
Posts: n/a
 
      12-30-2013
On Sat, 28 Dec 2013 11:30:21 -0500, Eric Sosman wrote:

> Finally, to your "backtracking counter" loop: I really,
> really don't like it. A better formulation, I think, would be
>
> for (i = 0; i < len; ) {
> if (needs_deleting(arr[i])
> len = del_at(i, len, arr);
> else
> ++i;
> }
>
> ... because the reader will not be fooled by the familiar-looking `i++'
> in the first line and perhaps overlook the unfamiliar in-loop
> adjustment. Seeing no index adjustment at all in the `for', he will
> look inside the loop to learn what happens to `i', and (I think) his
> route to understanding will be a shorter one.


See, that's *exactly* the kind of response I was looking for. It teaches
me an alternative way of doing things I myself had doubts about when
doing them the way I did them.

As to the 'elegance' discussion, I though for a while what word to use
and basically chose 'elegance' over others because I thought it had the
higest chance of conveying the intended meaning and producing the desired
response. The fact I got the response I wished for basically proves my
choice right.
 
Reply With Quote
 
Matt
Guest
Posts: n/a
 
      12-30-2013
On 29/12/13 21:58, Matt wrote:
> On 28/12/13 20:19, Ben Bacarisse wrote:
>> you have a redundant loop in
>> getscore which is the time-limiting function right now. You can count
>> the matching colours without looping over colours.

>
> http://code.mattsmith.org.nz/masterm...ew_get_score.c


I plugged the new getscore in to the apple][ code and got a performance
gain. 15min wait on the first pass vs 20min previously.

I think I discovered something else though.

Looking at a single conceptually boolean int to see whether it is
necessary to do something to something seems like a trivial operation.

What if you did it 1296 * (15 * 1296) times and only 1296 * (1 * 1296)
of them were necessary? Could this slow your program down?

If anyone is curious the offending code is the loop at line 178 of
http://code.mattsmith.org.nz/mastermind/aztecc65/main.c

I think Eric was on the money when he said

> I suspect something's
> seriously amiss with your setup


And I was on the money when I said

> I'm pretty sure it'll turn out to be my program


Matt.
 
Reply With Quote
 
Jorgen Grahn
Guest
Posts: n/a
 
      12-30-2013
On Fri, 2013-12-27, Tim Prince wrote:
> On 12/27/2013 5:45 AM, Willem wrote:
>> Matt wrote:
>> ) I'm sure I've read somewhere that it's considered bad practice to modify
>> ) the value of the variable on the right of a comparison operator inside
>> ) the loop concerned.


>> Perhaps the 'bad practice' you read about was this idiom, which is used to
>> avoid 'break' statements:
>>
>> for (i = 0; i < len; i++) {
>> if (needs_ending(arr[i])) {
>> i = len;
>> } else {
>> do_something_with(arr[i]);
>> }
>> }


> This one may prevent or break optimizations based on setting the loop
> count prior to entering the loop. The break also would prevent such
> optimizations, but the compiler would have no excuse for missing it.


It's also terribly ugly, IMO. "The cure is worse than the disease" is
a phrase which comes to mind. A big part of the appeal of for loops
is "look, here's all you have to know about how 'i' changes, in one
single line".

(I don't think I've seem it before, except of course the form with an
explicit "please stop the loop" flag -- 'i < len && !stop')

/Jorgen

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
 
Reply With Quote
 
Eric Sosman
Guest
Posts: n/a
 
      12-30-2013
On 12/30/2013 4:30 PM, Matt wrote:
> On 29/12/13 21:58, Matt wrote:
>> On 28/12/13 20:19, Ben Bacarisse wrote:
>>> you have a redundant loop in
>>> getscore which is the time-limiting function right now. You can count
>>> the matching colours without looping over colours.

>>
>> http://code.mattsmith.org.nz/masterm...ew_get_score.c

>
> I plugged the new getscore in to the apple][ code and got a performance
> gain. 15min wait on the first pass vs 20min previously.


Still seems far too long. See below.

> I think I discovered something else though.
>
> Looking at a single conceptually boolean int to see whether it is
> necessary to do something to something seems like a trivial operation.
>
> What if you did it 1296 * (15 * 1296) times and only 1296 * (1 * 1296)
> of them were necessary? Could this slow your program down?


If you drank fifteen times your normal intake of beer,
could this slow *you* down?

Might this account for your fifteen minutes? Let's use the
back of this handy envelope here: 25e6 tests divided by 900 seconds
is 28000 tests/sec, or 36 microseconds/test. You've mentioned that
you're using an emulator for an elderly machine, and "36 MHz" might
be in the right ballpark. If the host machine's instruction set is
dissimilar to that of the emulated system, the emulator may well
be an interpreter; such things often execute dozens to hundreds
of host instructions for each emulated instruction. If the test
and branch amounts to four or five emulated instructions, a twenty-
fold dilation would turn "36 MHz" into "3 or so GHz," which would
be something akin to what one would get from a present-day machine.

Of course, this doesn't *prove* the extra work is soaking up
all or even most of your time, but the numbers seem plausible and
do not rule out the possibility. I think you'd do well to give
this matter further attention.

--
Eric Sosman
(E-Mail Removed)d
 
Reply With Quote
 
Jorgen Grahn
Guest
Posts: n/a
 
      12-30-2013
On Sun, 2013-12-29, Phil Carmody wrote:
....
> I notice that one example was a for() and the other was a while().
> I'm a great believer that people over-use for() - I hate seeing ``; )'',
> for example.


Me too, but I don't seem to see it a lot. My feeling is people abused
for() more in the past, perhaps because the optimizers were worse.

> That immediately says "should have been implemented as a
> while loop" to me.


Yes. 'for' is IMHO good for a few (but common!) cases only.

/Jorgen

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
 
Reply With Quote
 
Jorgen Grahn
Guest
Posts: n/a
 
      12-31-2013
On Sun, 2013-12-29, Seebs wrote:
> On 2013-12-29, Eric Sosman <(E-Mail Removed)> wrote:
>> I think that "elegance" means different things to the two
>> of us (eye of the beholder, again). The quality you describe
>> as "elegance" is something I'd prefer to call "clarity," and I
>> agree that it's a desirable attribute regardless of whether you
>> call it clarigance or eleganity.

>
> Hmm. You may have a point.
>
>> ... and that's why I don't think "elegance" is a useful
>> criterion: If you can't measure it, you can't tell whether it's
>> present or absent, or to what degree.

>
> I'm not sure that's right. Or rather: Even if things are subjective,
> they may still be useful criteria.


Yes. (Also, even the interesting properties you /can/ measure are
usually infeasible to measure. You won't have a team of psychologists
and a study group handy when it's time for code review ...)

Almost all conflicts I have with coworkers, people on Usenet, previous
authors of code I have to maintain, etc ... are about subjective
things. E.g. the code is reasonably correct, but it's not as easy
(pleasant) to work with as I'd like it.

Frustratingly, too often (most of the time, it seems) what's readable
to one person is not very readable to all others. Only the people who
just don't care are unaffected.

Clarity as a concept doesn't seem a lot more helpful. Your background
and way of thinking has too much of an impact on what you see as
"clear".

/Jorgen

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
The node.js Community is Quietly Changing the Face of Open Source Rodrick Brown Python 2 04-17-2013 04:47 PM
Re: The node.js Community is Quietly Changing the Face of Open Source Sven Python 0 04-16-2013 04:41 PM
Re: The node.js Community is Quietly Changing the Face of Open Source Ned Batchelder Python 0 04-16-2013 04:25 PM
Is there a difference between the use of the word montage vscollage Danny D. Digital Photography 8 04-15-2013 02:24 PM
Windows 8 - so bad it's hastening the death of the PC? ~misfit~ NZ Computing 18 04-15-2013 04:15 AM



Advertisments