คำสั่ง break จะยุติการวนซ้ำและโอนการดำเนินการไปยังคำสั่งหลังการวนซ้ำทันที
คำสั่ง Continue ทำให้การวนซ้ำนั้นข้ามส่วนอื่นๆ ของร่างกายและทดสอบเงื่อนไขซ้ำทันทีก่อนที่จะทำซ้ำ
เมื่อพบคำสั่ง break ภายในลูป การวนซ้ำจะสิ้นสุดลงทันทีและการควบคุมโปรแกรมจะกลับมาทำงานต่อในคำสั่งถัดไปหลังจากวนซ้ำ
คำสั่ง Continue ใน C# ทำงานเหมือนกับคำสั่ง break อย่างไรก็ตาม แทนที่จะบังคับให้ยุติ ให้บังคับให้มีการวนซ้ำรอบถัดไป โดยข้ามโค้ดใดๆ ที่อยู่ระหว่างนั้น
ต่อไปนี้เป็นรหัสที่สมบูรณ์สำหรับใช้คำสั่งดำเนินการต่อไปในขณะที่วนรอบ -
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* loop execution */
while (a > 20) {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
} ต่อไปนี้เป็นตัวอย่างของคำสั่งแบ่ง -
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}