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
would stop theforeach
loop completely,continue
would skip to the nextDataRow
.By example
Prints 1, 2, 3 (on separate lines).
Add a break condition at i = 2
Now the loop prints 1 and stops.
Replace the break with a continue.
Now to loop prints 1 and 3 (skipping 2).
Thus,
break
stops the loop, whereascontinue
skips to the next iteration.break causes the program counter to jump out of the scope of the innermost loop
Works like this
continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.
Works like this
As for other languages:
I used to always get confused whether I should use break, or continue. This is what helps me remember:
When to use break vs continue?
Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.