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;
}
}
Ruby unfortunately is a bit different. PS: My memory is a bit hazy on this so apologies if I'm wrong
instead of break/continue, it has break/next, which behave the same in terms of loops
Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this
You can however do this
HOWEVER, a lot of ruby code 'emulates' a loop by using a block. The canonical example is
As it is much more common for people to want to do things with the result of a block, this is where it gets messy. break/next mean different things in the context of a block.
break will jump out of the code that called the block
next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.
So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)
Break
Break forces a loop to exit immediately.
Continue
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.
All have given a very good explanation. I am still posting my answer just to give an example if that can help.
Here is the output:
So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3
Here is the output:
So 3[Printed] will not be displayed as there is continue when i == 3