views:

180

answers:

7

I break the code of the for loop without using break like I have for loop given below.And when i is 1 or 2 or 3 or any else but if condition is true then loop will be terminated because i will be 5 if the condition is true.And so NO need of break is needed there.Beacause I do not want to use break.I have done like this here.It works.

int myCondition=0;
bool flag=false;
for(int i=0;i<5;i++)
{
   if(myCondition==0)
   {
       flag=true;
   }
   if(flag)
       i=5;
}

But now I want to use foreach loop and in this loop when some condition is true then I want to break the foreach loop code.So what should I do here for breaking the foreach loop code without using break ? Like in the above for loop I have initialize i to 5 when condition is true.In the foreach loop anything like that to do to avoid break.

+4  A: 

This is probably going to get me downvoted... but you should use the break keyword.

Failing that:

foreach(var foo in bar)
{
  if(condition)
  {
    //perform normal loop code
    //set condition if required.
  }
  //otherwise do nothing - the loop will iterate all the way to the end without 
  //doing anything.
}

You could be more expressive and use if(condition){ /*blah*/}else { continue; } inside the loop - but either way it does the same thing.

You can't do much else to break out of a for each other than:

  • Use break
  • Throw an Exception
Andras Zoltan
no it gets you upvoted :) I'm of the same opinion so +1
Razzie
+1  A: 

Not using break in your for(;;) loop is a serious stylistic mistake. But you'll get away with it. But not when you use foreach, you have to use the break keyword.

Pay attention to the title of this blog post.

Hans Passant
@nobugz: good point on the *blog*.
dboarman
Thanks for the answer Sir...
Harikrishna
+2  A: 

In general, the 'pattern' you describe here is a code smell. It is NOT a good idea to change the index variable in a for-loop. It can result in unreadable, hard-to-maintain code, especially if the loop grows large.

That being said, why would you not want to use the break keyword. It is meant for this purpose, and whatever downside it has (in your opinion) is still a far better solution than the one you describe here.

Last, I see no way to do the same thing using a foreach loop in a sensible way.

Razzie
Thanks for the answer
Harikrishna
+10  A: 

You should use what's in the language. There's no need to avoid break - just use it. Or to put it another way, "I don't want to use break" is not a good enough justification: if you think you've got a really good reason not to use it, then you should explain that reason. Don't hobble yourself by pretending perfectly reasonable features don't exist, and coming up with convoluted schemes to avoid them.

Jon Skeet
Thanks for the answer Sir..
Harikrishna
Would you apply this same reasoning to `goto`? Or would you turn it around for `goto` and say that you better have a good reason *to* use before it's acceptable?
tvanfosson
@tvanfosson: If you're in a situation where `goto` provides the cleanest way to express yourself (which is *very occasionally* the case in a switch statement) then yes, I'd use the same reasoning. It's considerably rarer than `break` though.
Jon Skeet
goto is also a keyword that is there for a reason. If you have the perfect candidate for 'goto' in your code, why not use it?
Axarydax
@Axarydax - I don't think anyone disagrees there, just that the "perfect candidate" is very, very rare.
Nick Craver
@Jon - I'd say there's a presumption of guilt for a `goto` rather than a presumption of innocence. I can't really think of any situations where I'd prefer it over another mechanism except as a glorified `break` -- transferring control from the innermost loop of several nested loops to the statement following the looping constructs. Even the switch case I'd prefer to refactor to call a method rather than transfer to a block via `goto`.
tvanfosson
@Jon -- or more plainly, I've always got a good reason **not** to use a goto, what I need is a **better** reason to use it than not.
tvanfosson
+8  A: 

Don't do it.

Your manipulation of 'i' in the for loop is questionable already. Trying to mess with the iterator in a foreach-loop would be downright dirty. If it compiles at all.

I would write your example with a break or as:

bool myCondition=false;
for(int i=0;i<5 && !myCondition;i++)
{
   ....
}

In a foreach loop, when you're done before the entire sequence is complete, just call break

Henk Holterman
Thanks for the answer..Is it ok to use goto in our code ?
Harikrishna
@Harikrishna: The difference between break and goto is that usually there are cleaner ways of expressing the same control flow than using goto; break is a natural way of expressing a reasonably common control flow.
Jon Skeet
Reluctantly, because of the limitations of `break`, we use `goto` to get out of nested loops.
Henk Holterman
@Henk: That's where the labeled break in Java is occasionally useful. Mind you, I find that refactoring the loops into separate methods often leads to cleaner code at that point anyway.
Jon Skeet
@Jon, agreed. A concrete example could probably be solved even better with LINQ. But it is a 'problem' with many gradations.
Henk Holterman
+1  A: 

Well, thats why there is this comand "break". I have no reasons why shouldnt you use it.

werd
Thanks for the answer
Harikrishna
A: 

Your code should absolutely be:

bool myCondition = false;

for(int i=0;i<5;i++)
{
   // do stuff
   if(myCondition)
      break;
}

Not only are you using the commands (i.e. tools) provided by the language, but you are keeping the code very readable, and maintainable. The break command is fundamental to the language.

Trying to come up with some reason not to use break is like doing math on a calculator -- literally, turn the calculator over, get a silver paint marker, and do some math. You are crippling yourself by not using the tools in front of you.

dboarman