How do I exit a for loop in C#

M

Mark Rae

What is the sytax for exiting a for loop in C#?

continue; will stop processing in the current loop and jump straight to the
next

break; will exit the entire loop
 
B

Brady Kelly

What is the sytax for exiting a for loop in C#?

To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.
 
J

Jon Skeet [C# MVP]

Brady Kelly said:
To be picky, you should use a while loop and include whatever would
cause an exit from your for loop in the loop condition of the while
loop.

I disagree on that. There are *loads* of times where you basically just
want to get out of a loop at a certain point - and that may be
different points in the execution of the block within the loop.

It's one of those "rules" which might sound okay in principle, but ends
up making the code completely unreadable in practice.
 
R

Roy Fine

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.

"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)

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.

regards
roy fine
 
J

Jon Skeet [C# MVP]

Roy Fine said:
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?
 
B

Brady Kelly

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

Jon Skeet [C# MVP]

Brady Kelly said:
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.

If it's readable, then in what way is it "not correct"?

There's no point in adhering to rules which are counter-productive. If
using a for loop gives you greater readability than using a while loop
and with no other adverse effects, then go for it - ignore rigid rules
which attempt (and fail) to cover every situation.

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

Roy Fine

Jon

Read CodeComplete first.

It is not about finding exceptions to the rule, or even about making your
own rules. Rather, it is about following the rules that are already
accepted.

regards
roy
 
R

Roy Fine

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.

then you have no standard, and you have no uniform style - what you have
just described is ad hoc, and that's what get's serious programs into
trouble.

roy
 
M

Michael Voss

Hi !

Aaron Ackerman said:
What is the sytax for exiting a for loop in C#?

One might as well want to put the loop in a new method and just return from
that method with whatever you'd like to give as a return value whenever you
like (other oo languages do not have (or need) something like "break" or
"continue")...
 
J

Jon Skeet [C# MVP]

Roy Fine said:
Read CodeComplete first.

It is not about finding exceptions to the rule, or even about making your
own rules. Rather, it is about following the rules that are already
accepted.

But why accept them if they're silly? A rule such as "never break out
of a for loop, even if it means you've got to write a far less readable
while loop" *are* silly. I refuse to accept any argument *solely* on
the grounds that other people have accepted it. If it can't stand up on
its own merits, I'm not going to accept it.

So, where's the *more* readable while loop version of the code I
posted?
 
J

Jon Skeet [C# MVP]

Roy Fine said:
then you have no standard, and you have no uniform style - what you have
just described is ad hoc, and that's what get's serious programs into
trouble.

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

Jon Skeet [C# MVP]

Michael Voss said:
One might as well want to put the loop in a new method and just return from
that method with whatever you'd like to give as a return value whenever you
like (other oo languages do not have (or need) something like "break" or
"continue")...

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.

Just because other languages don't have a certain feature doesn't mean
that it shouldn't be used.
 
J

Jon Skeet [C# MVP]

Roy Fine said:
read this
http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=i36b25.a92
.ln%40sol.dimaga.com&rnum=2&prev=/groups%3Fq%3DMcConnell%2Bcode%2Bcomp
lete%2Bgroup:comp.*%26hl%3Den%26lr%3D%26ie%3DUTF-8%26group%3Dcomp.*%26
selm%3Di36b25.a92.ln%2540sol.dimaga.com%26rnum%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?
 
R

Roy Fine

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
 
M

Michael Voss

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top