Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# loop - break vs. continue

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;     } } 
like image 475
Seibar Avatar asked Aug 08 '08 21:08

Seibar


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


2 Answers

break will exit the loop completely, continue will just skip the current iteration.

For example:

for (int i = 0; i < 10; i++) {     if (i == 0) {         break;     }      DoSomeThingWith(i); } 

The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here:

for (int i = 0; i < 10; i++) {     if(i == 0) {         continue;     }      DoSomeThingWith(i); } 

Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.

like image 103
Michael Stum Avatar answered Sep 21 '22 06:09

Michael Stum


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.

like image 36
JeremiahClark Avatar answered Sep 21 '22 06:09

JeremiahClark