473,756 Members | 8,110 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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::itera tor i = mySeq.begin(); i != mySeq.end(); ++i )
{
i->doSomething( );

if( *i->hasCertainCond ition() )
{
i->doSomethingEls e();
//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::itera tor i = mySeq.begin();
for( i; (i != mySeq.end()) && (not i->hasCertainCond ition()); ++i )
{
i->doSomething( );
}
//if loop terminated early, doSomethingElse
if( i != mySeq.end() )
{
i->doSomethingEls e();
}

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 2444
On 2007-11-22 07:27:14 -0500, werasm <we****@gmail.c omsaid:
>
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...@earthl ink.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.c omwrote,
>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_fl ag=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 comprehensibili ty 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
3171
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 containing info from the database that the client is interested in. Problem is that the ASP file exits as soon as it has sent about 50 or so records to the Mercury/32 mail server on the local Ethernet. No error message or program execution...
43
5598
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 fallacy built on the assumption of mythical infinite all powerfull machines. In reality we deal with finite machines that are capable of two states in a loop, they either terminate, or repeat themselves. In the mythical halting problem scenario...
23
2209
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 = 5;
6
11077
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
2209
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 this nested loop to make sense? This is the last holdup to completion of my silly project. Explaining it from the inside - out, I want to fill a 120-col X 40-row array with data from a file containing 120 data records of 5 2-digit entries per...
8
2858
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++) For(i=0; i<=K; i++)
669
26159
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 paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990. http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
23
2087
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 coward! 8473: Q1->P2 HAHAHAHAHA! 8381: G3->EVERYONE ok ok ok! But when I run my progam it only prints the second line:
44
4320
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
10040
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9713
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8713
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3806
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.