473,839 Members | 1,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I exit a for loop in C#

What is the sytax for exiting a for loop in C#?
Nov 16 '05
65 65092
Roy Fine <rl****@twt.obf uscate.net> wrote:
read this http://groups.google.com/groups?hl=e...adm=i36b25.a92
.ln%40sol.dimag a.com&rnum=2&pr ev=/groups%3Fq%3DMc Connell%2Bcode% 2Bcomp
lete%2Bgroup:co mp.*%26hl%3Den% 26lr%3D%26ie%3D UTF-8%26group%3Dcom p.*%26
selm%3Di36b25.a 92.ln%2540sol.d imaga.com%26rnu m%3D2


I don't need to be persuaded that it's a popular book. That doesn't
mean that every line of it should be accepted without looking at the
arguments presented, does it?

I note that you haven't actually tried to really present the arguments
- you've just said that someone who is well respected made the
argument, and left it at that.

Why not address the actual issue, rather than just appealing to
authority? If his arguments stand up, present his arguments. If they
don't - well, then why should you accept them just because he makes
good points about *other* situations?

Why not address my specific example where I believe a for loop is more
readable than a while loop?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #21
Jon

the OP was quite specific - how do you exit a for loop? the answer is in
the header. if that doesn't work, or is too complicated, then use the while
loop. if you have specific reasons for otherwise, they are specific - keep
them to yourself and don't try to inject them as a norm or standard or as a
general excuse for not adhering to a style, esp when said style is
universally adopted, and well respected.

you seem to have a very strong sense of right and wrong, esp vis-a-vis
programming style - and you seem to be advocating your own set of style
guides. if that works for you, that's quite OK with me - I have no
misplaced perceptions of being able to convince you otherwise.

roy

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Roy Fine <rl****@twt.obf uscate.net> wrote:
read this

http://groups.google.com/groups?hl=e...adm=i36b25.a92
.ln%40sol.dimag a.com&rnum=2&pr ev=/groups%3Fq%3DMc Connell%2Bcode% 2Bcomp
lete%2Bgroup:co mp.*%26hl%3Den% 26lr%3D%26ie%3D UTF-8%26group%3Dcom p.*%26
selm%3Di36b25.a 92.ln%2540sol.d imaga.com%26rnu m%3D2


I don't need to be persuaded that it's a popular book. That doesn't
mean that every line of it should be accepted without looking at the
arguments presented, does it?

I note that you haven't actually tried to really present the arguments
- you've just said that someone who is well respected made the
argument, and left it at that.

Why not address the actual issue, rather than just appealing to
authority? If his arguments stand up, present his arguments. If they
don't - well, then why should you accept them just because he makes
good points about *other* situations?

Why not address my specific example where I believe a for loop is more
readable than a while loop?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #22
HI !
"Jon Skeet [C# MVP]" wrote:

[...snip...]
Sometimes that's appropriate. Other times, it's not. In a few cases it
can increase the readability to move the method out - but not in
*every* case.
I think, moving the loop into another method will lead to shorter methods in
most (if not close to all) cases and thus increase readability most of the
time - but that's just my opinion...
Just because other languages don't have a certain feature doesn't mean
that it shouldn't be used.


[...snip...]

Of course not; I was merely presenting another alternative to the op. But,
on the other hand, being given a certain feature by the designers of a
language does not make this feature the #1 choice in all of the cases (or
even in the majority of the cases), either.

Nov 16 '05 #23
Roy Fine <rl****@twt.obf uscate.net> wrote:
the OP was quite specific - how do you exit a for loop? the answer is in
the header. if that doesn't work, or is too complicated, then use the while
loop. if you have specific reasons for otherwise, they are specific - keep
them to yourself and don't try to inject them as a norm or standard or as a
general excuse for not adhering to a style, esp when said style is
universally adopted, and well respected.
It's clearly *not* universally adopted though - I see breaks and
continues in for-loops all over the place.

Just because the style a book espouses is *in the main* well respected
doesn't mean that *every* part of it should be.

I really don't see why criticising a supposedly respected style by
bringing up a reasonable common counter-example should make you suggest
I should keep that to myself. My example wasn't particularly specific
to me - it's the kind of loop lots of people need to write, a lot of
the time.

Why are you trying to stifle reasonable discussion of whether for loops
with breaks in should always be avoided?
you seem to have a very strong sense of right and wrong, esp vis-a-vis
programming style - and you seem to be advocating your own set of style
guides. if that works for you, that's quite OK with me - I have no
misplaced perceptions of being able to convince you otherwise.


I wasn't so much advocating my own set of style guides as suggesting
that the ones you were quoting should at least be backed up by
arguments better than "Well, it's in Code Complete, so it must be
right".

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #24
Michael Voss <mi**********@l vrREMOVE.deCAPS > wrote:
Sometimes that's appropriate. Other times, it's not. In a few cases it
can increase the readability to move the method out - but not in
*every* case.


I think, moving the loop into another method will lead to shorter methods in
most (if not close to all) cases and thus increase readability most of the
time - but that's just my opinion...


Yes, it will almost always lead to more, shorter methods. That
*doesn't* automatically increase readability, however. If you end up
needing to pass in several variables, some of them by reference, some
not, etc, then it'll quite possibly end up lowering readability.

Just thinking up the name for the replacement method is quite a good
guideline, I find. If it really doesn't have a good description because
it only makes sense in the circumstance of the calling method anyway,
it may well *not* be a good candidate for refactoring. (This guideline
doesn't always work, of course.)

Keeping methods short is a good rule of thumb, until you end up with
hundreds of methods, each of which is only two lines long, and which
just call other methods. There's a balance to be struck. (I don't
believe you were particularly arguing against that though.)
Just because other languages don't have a certain feature doesn't mean
that it shouldn't be used.


[...snip...]

Of course not; I was merely presenting another alternative to the op. But,
on the other hand, being given a certain feature by the designers of a
language does not make this feature the #1 choice in all of the cases (or
even in the majority of the cases), either.


Absolutely. A language feature should stand on its own merit: not on
the grounds that:

a) It's been included in this language, so it must be good
b) It's been excluded from other languages, so it must be bad
c) The author of Code Complete doesn't like it, so it must be bad

Those are all "meta-reasons" - what I'm far more interested is
concrete, specific reasons why it should or shouldn't be used in
specific situations.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #25

Why are you trying to stifle reasonable discussion of whether for loops
with breaks in should always be avoided?


1) I am not trying to stifle
2) the discussion has not risen to the level of reasonable
3) for loops with breaks in should be avoided - you want to make them
standard
roy
Nov 16 '05 #26
Roy Fine <rl****@twt.obf uscate.net> wrote:
Why are you trying to stifle reasonable discussion of whether for loops
with breaks in should always be avoided?
1) I am not trying to stifle


Really? What other purpose does a comment such as:

"if you have specific reasons for otherwise, they are specific - keep
them to yourself"

serve then? As soon as you start telling people to keep their opinions
to themselves during a discussion, you're stifling debate to my mind.
2) the discussion has not risen to the level of reasonable
That's because you've refused to engage with the meat of the
discussion, preferring to just recite the mantra of "do it because Code
Complete tells you to".
3) for loops with breaks in should be avoided - you want to make them
standard


And still you present no actual *reasons* - or indeed a more readable
while loop than my for loop.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #27
Jon Skeet [C# MVP] wrote:
I wasn't so much advocating my own set of style guides as suggesting
that the ones you were quoting should at least be backed up by
arguments better than "Well, it's in Code Complete, so it must be
right".


ok, my curiosity got the better of me, and I pulled my copy of Code
Complete of the shelf and had a look. Steve discusses Loop with exits
on page 326 and 327, he certainly doesn't advocate that they are not
used AFAICT, in fact he quotes the Software productvity consortium of
1989 that shows that in Ada this is the preferred kind of loop control
and that a student study showed that students scored 25% higher on a
comprehension test with this type of structure (Soloway, Bonar and
Ehrlich 1983)

For what it is worth, when Steve McConnell makes authoritive statements
in his book, they are always backed up by Hard Data, it is very rarely
a subjective thing. It's quite amazing to me that this book which is
now over 10 years old is still very relevant today I recommend it
highly. But I don't think anyone should become a slave to his
recommendations and conclusions, good judgment and experience count for
just as much as good texts.

Rgds Tim.
Nov 16 '05 #28
Roy Fine <rl****@twt.obf uscate.net> wrote:
BREAKS in a FOR loop means that you should have picked a WHILE loop instead.
Not necessarily. When there are multiple places in the loop where you
might want to break, it can be a complete pain to recode that as a
while loop. Either you end up with a horrendously large condition, or
you end up with a temporary variable which only serves to let you break
out - in which case you might as well break out directly, in my view.
If you accept McConnell's work in Code Complete as the style authority for
software construction - see section 15. The FOR loop is to be used when the
number of iterations is know aforehand.
I don't accept Code Complete to be flawless in every particular. That
seems a very bold statement about the for loop which would certainly
need more backing up than what you've presented. He's stated that *he*
likes to use the for loop only for simple loops, but at least in the
passages you've quoted, he hasn't stated *why*.
"The FOR loop is for simple loops. Most complicated looping tasks are
better handled by the WHILE loop." (pg 329)

"Limiting yourself to only one statement to control a loop's exit consdition
is a powerful way to simplify your loop." (pg 328)
Well, I disagree.
While you may disagree or have a personal preference or can cite some
specific instance to the contrary, Code Complete is hard to agrue with
because :
1) It's adopted by a lot of programmers and their repsective shops
That doesn't mean that every bit of it is absolutely perfect though,
does it? It makes sense to adopt most of a coding standard which you
mostly agree with, but not take the whole thing without allowing
yourself to disagree with any part of it.
2) The goal IS to create readable code (i.e. easier to understand, easier to
maintain)
On that we agree.
3) While opinions relating to programming style issues are like ears (every
one has at least two), McConnell certainly established the baseline - and
one has to build a strong case for the exceptions.


The exceptions seem pretty obvious to me. Here's an example - the task
is to see whether or not a string looks like a valid decimal number.
The rules are (for the purposes of this case):

o No whitespace anywhere
o No + or - (as that can be dealt with more effectively outside the
loop)
o A single decimal point is allowed (only allow '.' not ',')
o All other characters must be in the range '0'-'9'

To me, the simplest way of expressing that in C# is:

public static bool IsDecimal (string data)
{
bool gotPoint = false;

foreach (char c in data)
{
if (c != '.' && (c < '0' || c > '9'))
{
return false;
}
if (c=='.')
{
if (gotPoint)
{
return false;
}
gotPoint = true;
}
}
return true;
}

An alternative might be:

public static bool IsDecimal (string data)
{
bool gotPoint = false;

foreach (char c in data)
{
if (c=='.')
{
if (gotPoint)
{
return false;
}
gotPoint = true;
continue;
}
if (c < '0' || c > '9')
{
return false;
}
}
return true;
}

(Obviously the foreach can be easily recoded as a "real" for if you
want.)

What is the more readable while loop here?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #29
On Tue, 6 Apr 2004 20:10:32 -0400, "Roy Fine"
<rl****@twt.obf uscate.net> wrote:
While you may disagree or have a personal preference or can cite some
specific instance to the contrary, Code Complete is hard to agrue with
because :
1) It's adopted by a lot of programmers and their repsective shops
2) The goal IS to create readable code (i.e. easier to understand, easier to
maintain)
3) While opinions relating to programming style issues are like ears (every
one has at least two), McConnell certainly established the baseline - and
one has to build a strong case for the exceptions.

that's the way i see it, but i could be completly wrong.


I did say I was being picky when I said one should always use a while
loop to 'break out' of. In terms of readability, a loop body
shouldn't be long enough to create readability problems using any
approach, and in my opinion, although no correct, a 'break' from a for
loop is quite readable. It means, jump to the first statement after
all this loop code, and it doesn't require me to visit the pre/post
loop check to evaluate conditions.
Nov 16 '05 #30

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

Similar topics

8
5420
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}'' 'else if (choice == 27) exit(0) } }' Here is my program (Simple loop to display currency equivalencies based
8
10768
by: Edwinah63 | last post by:
Hi Everyone, in vb6 i was able to execute the following code and it would close the children is the reverse order they were opened eg the last child opened was the first child to close. in mdiparent i had this code i = Forms.Count - 1 Do Until i = 0
4
2145
by: Microsoft | last post by:
I have a for loops that goes from 1 to 256 I test the number and exception is thrown if there is an error. How do I get the program to stop in the middle of the loop and go to the next increment if an exception is thrown. I can only figure out how to exit the loop. 'read the text file
32
2618
by: cj | last post by:
When I'm inside a do while loop sometimes it's necessary to jump out of the loop using exit do. I'm also used to being able to jump back and begin the loop again. Not sure which language my memories are of but I think I just said loop somewhere inside the loop and it immediately jumped back to the start of the loop and began again. I can't seem to do that in .net. I this functionality available?
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 .
2
2102
by: nabman | last post by:
I am reading a txt file, I have a txt file(customers.txt) that is read, with account numbers and passwords. Once the user enters a account number and password it should read the file and if there in there it will show the second form and end the loop. The probelm I am having is when I enter a acct # and password that is maybe the third entry in the file it is hitting the "else" statment and displaying my msgbox. What is the code I can put in...
11
3019
by: Andreig | last post by:
Gentlemen I cannot figure out the following: I have a loop inPrivate Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint Pressing a key I am checking what key was pressed and come back to the loop. Thanks for help
4
2688
by: kenneth6 | last post by:
for(int i=0; i<100; i++) { if(mark==TMark) { return i; cout << i << endl; break; } else {
11
12182
by: icarus | last post by:
Hi, this is a simple temperature converter (Fahrenheit to Celsius to Kelvin). Using gcc 4.0. The user is supposed to enter q or any other non-character to exit the program. Problem with this code: I enter 'q' as soon as the program starts. It hangs. Then run it again. Enter a number, it executes fine. But when I enter q, it repeats last number and it doesn't 'pay attention' to the letter
7
2731
by: csharpula csharp | last post by:
Hello, I am iterating through objects and have the following case: foreach (classA objectA in classAList) { if (classA.count0) { //now I need to get out of the foreach loop if so,otherwise to keep iterating
0
9854
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10903
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
10290
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
9425
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 project—planning, coding, testing, and deployment—without 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
7827
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
7015
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
5865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4482
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
3
3131
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.