473,854 Members | 1,789 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 65100
Without having read the book I'd say your conclusion is baseless anyway Roy,
if I understand what you posted well enough. I've rearranged what you
posted to show what I mean.

"Roy Fine" <rl****@twt.obf uscate.net> wrote in message
news:O3******** ******@TK2MSFTN GP12.phx.gbl...
[original post:]
BREAKS in a FOR loop means that you should have picked a WHILE loop instead.
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.

[rearranged] "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 condition is a powerful way to simplify your loop." (pg 328)
therefore (according to Roy's interpretation and not stated explicitly in
the book): BREAKS in a FOR loop means that you should have picked a WHILE loop

instead.

In other words, I find myself able to agree 100% with the first two
statements but find the third doesn't even make logical sense. Either of
these kinds of loops require either breaks or that the test condition is
unable to change within the loop by definition, a constraint that seems
implausible when facing real-world algorithm problems (without refactoring
the code to ridiculous levels).

Let my try this one more way... the quotes are clear to say "Most" and "is
*A* way", and don't seem to speak in absolutes at all to me, unlike your
statement.
Nov 16 '05 #61
Jon,

seems like you have quite a following -- lot's of luck.

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:
"if you have specific reasons for otherwise, they are specific - keep
them to yourself"


You cut and past at will -- here is the entire quote -
>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.


AND DONT TRY TO INJECT THEM AS NORM OR STANDARD OR AS ....


Yes, note the "and" here. You were telling me to keep my opinions to
myself. In other words, you were telling me to shut up and not to
criticise a "well accepted" practice.
You want to adopt your way because you have found a circumstance that make sense. That's fine, but you must accept that it is then an exception, and then you need to adopt exception handling - i.e. comments the code to
mitigate the complexities.


No, I *don't* believe it's an exception. I believe that quite
*frequently* using breaks (or returning from the for loop itself) leads
to more readable code than rewriting it as a while loop.
If you want your style to be generally adopted, then publish them and let them stand the test of peer review.


It's not so much that I particularly want my style to be generally
adopted - I just take issue with a universal dictum that I should write
code in a particular way solely because someone else thinks it's a good
idea. If it's a good idea, say *why* it is.
But keep in mind that your styles are
against currently accepted styles, so the burden will be substantially
higher; you have to first show that the existing standard is bad, and then show that yours is clearly better. That is a VERY tough process.


If it's so far against currently accepted styles, would it surprise you
if virtually every significant piece of published code contained breaks
in that style? I bet if we were to look through code for, say, Apache,
Tomcat, JBoss, Linux, ROTOR etc, we'd find plenty of examples which
break the rule.

Note that I certainly haven't proposed that while loops should be
avoided - just that you shouldn't *forbid* yourself from breaking out
of a for loop, as that can end up with more readable code than
converting the whole thing into a while loop.
You want to exchange jabs based on specifics, and as you noticed, I
steadfastly refuse - to make a proof for a generalized statement based on specific examples, there would have literally thousands of examples - and that is not the way a proof is done here.


If a rule does not *work* universally, it should not be *adopted*
universally, or espoused universally. It makes no sense to pretend I'm
the only one who ever has to write methods such as the one I posted.

A proof cannot be made *for* a style rule based on one specific example
- but if one specific example works *against* a style rule, that's
proof that it shouldn't be applied universally.
I would gladly review any code and help you rework it to become more
supportable, based as a style guide - you dictate the style guide, and I'll follow the rules. It seems that you either knew nothing of McConnell's work or a priori dislike for it. If thats the case, I can accept that.


I don't have an a priori dislike for it - I have a dislike for being
told *what* to do, but not *why* I should do it. I very much doubt that
McConnell fails to give reasons, so why are you so averse to sharing
them and debating them? Do you consider Code Complete to be "above"
peer review itself?

If you would gladly review code, then please review the code I've
already provided, and rewrite that according to McConnell's guide -
we'll see how readable it ends up.

(Of course, the whole of the above is based on the premise that
McConnell *does* universally forbid breaking out of for loops.
According to another post, he doesn't do so at all.)

--
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 #62
Daniel Billingsley wrote:
Roy, I've never found a single comment from Jon to be unworthy of a listen,
even when I've disagreed strongly. I, like many here, value his OPINIONS on
many topics as much as you seem to value some book.
I agree.

People should always have an open mind to different ideas/styles when it
comes to programming, even though it can be very difficult when it
involves something that you may have practised for years (e.g. my
quabble about C-style returning, since I've been using something
different for a long time).

Further, I think Jon only helps on a subject when he knows it
*inside-out*. So if I ever read one of his posts and disagree about
something, I usually take the time to investigate the details of *why* I
disagree, since it may well be that he is making a good point through
greater experience of the particular subject.
I never got the impression that Jon said the exception should be the rule as
you are trying to claim, so it seems at this point this is largely a
misunderstandin g anyway.
I agree.
Can we just leave this as Roy things standards should never have exceptions
and Jon does?

If you want my opinion (LOL), way back in high school I came up with this
"All rules have exceptions or get broken. The main difference is the former
remains under the control of the rule maker." I've seen this same kind of
(what I call) fanatic adherence to "patterns", where people think first and
foremost in terms of trying to fit every new problem they face into some
existing pattern.


Here's my £0.02: there are no *rules* here, there are only *guidelines*.
These guidelines should be followed *in general*, but /sometimes/
there's a more elegant solution which doesn't follow the guideline, and
enforcing the guideline here would be over-kill.

I think Jon's decimal number example in this thread illustrated this
perfectly.
Nov 16 '05 #63

"Daniel Billingsley" <db**********@N O.durcon.SPAAMM .com> wrote in message
news:Or******** ******@TK2MSFTN GP10.phx.gbl...
Roy, I've never found a single comment from Jon to be unworthy of a listen, even when I've disagreed strongly. I, like many here, value his OPINIONS on many topics as much as you seem to value some book.

And are letting you love for Jon get in the way of the real message.

My original post was towards the style - that is "a general standard that
all strive to follow". The keyword is strive! Its not about forcing or
policing - it is about developing strong code. It is not about stiffiling
one's creativity - it's about adopting a style that server the greater good.

1) Use the FOR loop when you need to execute a set of statements a specific
number of times.
2) Use the WHILE loop when you want to execute a set of statememts while
some expression evaluates to boolean TRUE
3) Use the simple loop with a break when 1) or 2) don't fit the problem at
hand
4) Keep all exit/break statements together

This is not just C# stuff - it good coding stuff. This works with ADA, C++,
C#, VB, PL/SQL, and so on.

If you are the only programmer in the company, then ignore all of the above,
sling your code, attack with vengence all who disagree - and do what feels
good at the time. If you are a lone wolf programmer, then you are not the
subject of this rant.

If you are one of a team of a dozen or so working on a project, and
especially if you are following the X-Programming model, you'll be glad
there is a style guideline in place. Everyone doing it their own way is bad
for all. Everyone doing it one way is good for the project. If you don't
like the above guidelines, adopt you own. If they are good guidelines,
those that you adopt, publish them for all, and we will all forever be in
your debt.

It is not that developing with these guidelines holds any grand promise -
rather that developing sans any is most certainly a bad thing. And to
eschew guidelines in general because one can always think of a case where
the guidelines "just don't feel right", is arrogant, silly, and just not a
nice thing to do!

My only problem with Jon is his rejection of the generalized style (any
style, but specifically one that has been generally accepted as good). Jon
presented one case that he where felt the guideline was inappropriate - so
he tossed the entire guideline set out the window - rather than offer his
suggestions as an exception to the style, which is allowed when dealt with
accordingly.

And I didn't pick up just any book - Code Complete is a book that any/every
serious programmer should have handy -- right beside the Knuth set, and
others like Box, Richter, Prosise, Petzhold, Brown, and so on. It should be
an embarrassment for any serious programmer to not have ever heard of the
book. And when it is mentioned, I find it amazing that so many would scoff
it aside - just because "it ain't no good 'cause I ain't heard of it". And
it is not that this book necessarily in the category of GREAT book - it'll
never make it to a movie, it will never replace the Bible, it's not a book
you'd take to the beach. Code Complete is just a book, one book of many on
the subject.

And you seem to be of the mind that "all rules are made to be broken". The
prisons of the land are full of those that adopted that saying as their
mantra. You make a giant, and unwarranted leap, when you suggest that my
position is any sort of fanatic adherence to "patterns". Give Code Complete
a quick read and get back with comments. (having read the book will
certainly enhance any serious programmer's CV)

I have offered my opinions, and listened to others - but as is all too often
the case in this newsgroup, it is quickly getting personal for some - and if
history has any impact on the future, it will degrade rapidly from here.
When the masses attack based on a discourse with one of their idols, then I
am reminded of a quote (one of hundreds of) from Swift's pen, something
about when you'll know that you are really on to something good (but as few
have ever heard of Code Complete, I suspect fewer have read Swift or Toole)

regards
roy fine

I never got the impression that Jon said the exception should be the rule as you are trying to claim, so it seems at this point this is largely a
misunderstandin g anyway.

Can we just leave this as Roy things standards should never have exceptions and Jon does?

If you want my opinion (LOL), way back in high school I came up with this
"All rules have exceptions or get broken. The main difference is the former remains under the control of the rule maker." I've seen this same kind of
(what I call) fanatic adherence to "patterns", where people think first and foremost in terms of trying to fit every new problem they face into some
existing pattern.

"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:
> "if you have specific reasons for otherwise, they are specific - keep > them to yourself"

You cut and past at will -- here is the entire quote -

>>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.

AND DONT TRY TO INJECT THEM AS NORM OR STANDARD OR AS ....


Yes, note the "and" here. You were telling me to keep my opinions to
myself. In other words, you were telling me to shut up and not to
criticise a "well accepted" practice.


Nov 16 '05 #64
Roy Fine <rl****@twt.obf uscate.net> wrote:
My original post was towards the style - that is "a general standard that
all strive to follow". The keyword is strive! Its not about forcing or
policing - it is about developing strong code. It is not about stiffiling
one's creativity - it's about adopting a style that server the greater good.

1) Use the FOR loop when you need to execute a set of statements a specific
number of times.
2) Use the WHILE loop when you want to execute a set of statememts while
some expression evaluates to boolean TRUE
3) Use the simple loop with a break when 1) or 2) don't fit the problem at
hand
4) Keep all exit/break statements together
If it's just a case of "striving" to follow the rule, and not enforcing
it rigidly, then you shouldn't have started your first post on the
subject with:

<quote>
BREAKS in a FOR loop means that you should have picked a WHILE loop
instead.
</quote>

That's not a statement of guidance, it's a statement of policing. If
you'd phrased it as:

<non-quote>
When you find yourself writing a BREAK in a FOR loop, consider whether
the loop could be more readably constructed as a WHILE loop instead.
</non-quote>

then I would certainly never have argued against it.

The above (and various other statements, such as that if you're not
following a standard to the letter, then it's doing you no good at all)
is what gives the impression that your position is indeed fanatical
adherence.

Rules *are* made to be broken, for the most part. Your claim that "the
prisons of the land are full of those that adopted that saying as
their mantra" is either a personal jab, or more fuel for the fire of
believing that you're happy to be a slave to rules rather than only
following them where it makes sense, or both.

If all of good coding could adequately be described in rules, there
would be no place for creativity.
My only problem with Jon is his rejection of the generalized style (any
style, but specifically one that has been generally accepted as good). Jon
presented one case that he where felt the guideline was inappropriate - so
he tossed the entire guideline set out the window - rather than offer his
suggestions as an exception to the style, which is allowed when dealt with
accordingly.


Have you been reading what I've been writing?

For instance:

<quote>
A *guideline* of "wherever you find yourself using a break in a for
loop, consider using a while loop" is one thing - but saying that it's
*incorrect* to use a break in a for loop is an entirely different
matter, IMO.
</quote>

and

<quote>
I have a uniform style - but one which can't be rigidly defined in
terms of rules, as it involves stylistic decisions which sometimes have
to be made on a case-by-case basis.

A standard doesn't have to be "in *every* case, you *must* do this" in
order to be useful.
</quote>

I've been suggesting that:
a) You don't have to throw out a whole coding standard just because you
don't like one piece of it. Within a team it's quite possible to pick
and choose parts of a common coding standard, agreeing on a different
coding standard for other sections.

b) You don't have to follow every part of a coding standard to the
letter in every situation in order for it to be useful. I can't work
out whether you agree with this or not - you seem to take issue with
the idea that rules are made to be broken, but you also don't like
being seen as forcing/policing a standard, or being fanatical about it.
Which is it to be?

c) Style issues should be justified by more than reputation.

Other than that, I've mostly been just asking for reasons to follow
this rule beyond "Code Complete says to do so" - oh, and for the more
readable version of my for loop, using a while loop. It's hard to tell
whether or not you've accepted that my example (which is reasonably
common-place) is a good example where the "rule" *can* be broken (in
which case, does that put you in the "prison" category too?) or not.
You've said you'd gladly apply whatever style I choose to try to
improve my code, but then you haven't done so despite being asked five
times prior to this post.

One thing I haven't mentioned is that different parts of a coding
standard are more or less important to agree on beforehand. For
instance, how exceptions are used, naming conventions, etc are very
important to teamwork, as consistency across an interface is very
important. Something like whether variables are declared at the top of
a class or at the bottom is much less important - when you're only
working to someone else's interface, it doesn't matter at all, and when
you're maintaining their code it's far from tricky to understand the
code just because the variables are in a different place to where you'd
put them.

--
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 #65

"Roy Fine" <rl****@twt.obf uscate.net> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..


And are letting you love for Jon get in the way of the real message.
No, I'm letting my love of truth and logic see through your BS.

My original post was towards the style - that is "a general standard that
all strive to follow". The keyword is strive! Its not about forcing or
policing - it is about developing strong code. It is not about stiffiling
one's creativity - it's about adopting a style that server the greater good.
1) Use the FOR loop when you need to execute a set of statements a specific number of times.
2) Use the WHILE loop when you want to execute a set of statememts while
some expression evaluates to boolean TRUE
3) Use the simple loop with a break when 1) or 2) don't fit the problem at
hand
4) Keep all exit/break statements together

This is not just C# stuff - it good coding stuff. This works with ADA, C++, C#, VB, PL/SQL, and so on.
True. However.. all you've done in #1 and #2 above is essentially define
what FOR and WHILE loops do. That could just as well have been written as
one guideline: "don't be an idiot, use the right type of loop".

Because that's the case, as I've already pointed out #3 isn't contrary to #1
and #2 at all as you'd like to suggest. Furthermore, #3 seems to be an
exception to the rule/guideline. Are you for or against exceptions, I'm
getting confused.

If you are the only programmer in the company, then ignore all of the above, sling your code, attack with vengence all who disagree - and do what feels
good at the time.

<snip >
And to eschew guidelines in general...
<snip >
My only problem with Jon is his rejection of the generalized style...

Niether Jon nor I have done anything of the sort.

I have offered my opinions, and listened to others - but as is all too often the case in this newsgroup, it is quickly getting personal for some


The only thing that is making it "get personal" is you putting words in
others' mouths, and you seem to be just arguing for argument's sake at this
point.

You seem to state now more or less simply that loops should be as
straightforward as possible and that breaks out of a loop are ok when they
are unavoidable. Sounds like what Jon has said, except possibly that he's
taken it to the level of saying that sometimes the breaks are in fact what
makes the loop more straightforward . For the sake of getting to the truth
on the matter, you've been asked you to make an example loop more
straightforward without using the break - you've effectively refused - even
though you had previously offered to do that very thing!

So Roy, put your money where your mouth is if you expect to have any kind of
credibility and not be ignored.
Nov 16 '05 #66

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

Similar topics

8
5421
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
2623
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
2734
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
9901
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
9752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10763
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
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...
1
7918
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
7082
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();...
1
4563
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
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3188
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.