In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?
Example:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
break
will exit the loop completely,continue
will just skip the current iteration.For example:
The break will cause the loop to exit on the first iteration -
DoSomeThingWith
will never be executed. This here:Will not execute
DoSomeThingWith
fori = 0
, but the loop will continue andDoSomeThingWith
will be executed fori = 1
toi = 9
.To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.
break
loop - looping is broken and stops.continue
loop - loop continues to execute with the next iteration.Simple answer:
Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)
There are more than a few people who don't like
break
andcontinue
. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include ado-while
ordo-until
style of loop.I tend to use
break
in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.I use
continue
when doing something with most elements of a list, but still want to skip over a few.The
break
statement also comes in handy when polling for a valid response from somebody or something. Instead of:You could eliminate some duplication and use:
The
do-until
loop that I mentioned before is the more elegant solution for that particular problem:No duplication, and no
break
needed either.if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.