473,386 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

for loop termination

Hi all,

I've been following the discussions concerning loops and
whether to break or terminate mimicking the condition etc.

I've had this recent case (which caused a bug) where I
had to do something on checking the condition, whereafter
exiting (the loop).

It went something like this:

for( Sequence::iterator i = mySeq.begin(); i != mySeq.end(); ++i )
{
i->doSomething();

if( *i->hasCertainCondition() )
{
i->doSomethingElse();
//essentially break out.
i = mySeq.end(); //Force terminate :-)
}
}

All in all the loop was more complicated, but this suffices the
example.
This caused a crash (as I recall). <iincremented after the loop was
completed whereafter the condition were checked. The increment of <i>
caused incrementing past the end (causing assertion).

I suppose there are other ways in which this could be done, but
<break>
statement would have solved the problem and would not have caused the
bug. Just merely (or naively perhaps) trying to be conventional caused
the
bug.

Of course one could have used (i = mySeq().end - 1), but <break>
seems less error prone to me.

It could also be noted that the loop is quite a rare case, where you
want to do something for each item, and if this causes the item
to change state, you want to do something else and then not
continue. Other possibilities that sprung to mind were:

Sequence::iterator i = mySeq.begin();
for( i; (i != mySeq.end()) && (not i->hasCertainCondition()); ++i )
{
i->doSomething();
}
//if loop terminated early, doSomethingElse
if( i != mySeq.end() )
{
i->doSomethingElse();
}

Using the original loop with a break seemed the cleanest to me. I've
noticed some "perhaps respected" posters shuns this approach.
What would you in general consider "the cleaner" solution?

One that I certainly don't consider cleaner is forcing the
termination
condition (as this is more error prone than break).

Regards,

Werner

Nov 22 '07 #1
3 2415
On 2007-11-22 07:27:14 -0500, werasm <we****@gmail.comsaid:
>
Probably begs the question:

Should we write tedious code merely to perfect the art of
having one exit point? To me the for/break solution is
much clearer.
I like it the way the official FAQ
http://www.parashift.com/c++-faq-lite/ puts it:

"Every interface you build has a cost and a benefit. Every reusable
component you build has a cost and a benefit. Every test case, every
cleanly structured thing-a-ma-bob, every investment of any sort. You
should never invest any time or any money in any thing if there is not
a positive return on that investment. If it costs your company more
than it saves, don't do it!"

So the question you have to ask yourself is this: What does the
perfection of the art cost you? What does it buy you?

To me, the best code is no code. What I mean here is the least amount
of code is almost always the most readable and maintainable code. Keep
it simple and straight forward.

If a simple break statement will do the trick and its use is clear and
obvious, then use it.

If you're nested deeply in many loops and you've reached a terminating
condition, then use a goto to jump out of all the loops. Quit messing
with setting up and checking for 'done' flags, or force the program
flow to plow through every loops' terminating conditions.

To me, the most important piece of the software is the class public
interfaces. How the internal implementation is done is much less
important.

--

-kira

Nov 22 '07 #2
On Nov 22, 4:14 pm, Kira Yamato <kira...@earthlink.netwrote:

To me, the most important piece of the software is the class public
interfaces. How the internal implementation is done is much less
important.
Yes, but I'm also the one that needs to do that internal
implementation
correctly, and per chance one day someone will need to do maintenance
by looking at existing code (implementation). I know that features
should not be added by modifying existing code (or at least by
modifying
as little as possible existing code). Therefore, when some does look
at the implementation (ever), I would hope that it would be crystal
clear to that someone what my intent was.

For this reason (I'm perhaps on your side here;-), I would want
to know - why not the break or the goto in a deeply nested loop
(the example being a case where not using break went wrong).

Kind regards,

Werner
Nov 22 '07 #3
On Thu, 22 Nov 2007 07:35:38 -0800 (PST) in comp.lang.c++, werasm
<we****@gmail.comwrote,
>For this reason (I'm perhaps on your side here;-), I would want
to know - why not the break or the goto in a deeply nested loop
(the example being a case where not using break went wrong).
The whole "structured programming" argument about writing loops with
a single point of exit was about whether or not the resulting code
was understandable and maintainable. If you can look at the result
and say "that's simple" you have done right. If you look at it and
say "okay, that trick will work" then beware.

In my opinion, the "it=end()" trick is in the latter category, and
"break" is usually simple. Not more than one "break". Before I
would use "it=end()" I would use "termination_flag=true".

For a nested loop, I will often put it in its own function and
"return" from the middle when the result is found, instead of
"break". Small functions that do a well-defined thing are worth
more for comprehensibility than single-exit is.
Nov 22 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Les Juby | last post by:
I have an application which loops through several thousand subscriber records, compares each subscriber's requirements to a database of businesses for sale, and then prepares and mails off an email...
43
by: Gremlin | last post by:
If you are not familiar with the halting problem, I will not go into it in detail but it states that it is impossible to write a program that can tell if a loop is infinite or not. This is a...
23
by: Mark Anderson | last post by:
A 'for' loop takes 3 arguments (initialize; test; increment). The 'test' must equate as true or false This doesn't work... x = 5; for (y=1; (y==5); y+=1) { alert(x * y); } ...nor does... x...
6
by: Shill | last post by:
I have several questions. In C, AFAIU, a for loop is just syntactic sugar for a while loop. for (i1; i2; i3) i4; is equivalent to i1 while (i2) {
5
by: Blankdraw | last post by:
I can't get this nested loop to break the outer loop at the 5th data value so control can proceed to the next array col and continue pigeon-holing the next 5 in its own column. Why can I not get...
8
by: Hardrock | last post by:
I encountered some difficulty in implementing dynamic loop nesting. I.e. the number of nesting in a for(...) loop is determined at run time. For example void f(int n) { For(i=0; i<=K; i++)...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
23
by: lisp9000 | last post by:
I wrote a small test program to read a file of data and print each line, but it's only printing the 2nd line out of 3 total lines. The test file, "foo.txt", has 3 lines: 7388: Zn->Z0 Run...
44
by: James Watt | last post by:
can anyone tell me how to do an infinite loop in C/C++, please ? this is not a homework question .
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.