break和continue的區別如下:
int i;
int n = 0;
for (int i = 1; i <= 10; i++)
{
if (i == 6) break;
n+= i;
}
上面的循環會因爲break語句而在i=6時提前終止,這樣n的最終值就是1+2+3+4+5
如將break換成continue
int i;
int n = 0;
for (int i = 1; i <= 10; i++)
{
if (i == 6) continue;
n+= i;
}
當i=6時就不會將i累加到n中,n的最終值是1+2+3+4+5+7+8+9+10,唯獨少一個6
總結:用break時,不管後面是否滿足for中條件,直接跳出循環。
用continue時,如果條件滿足時,跳出下面語句執行,返回到for循環的開頭,根據條件執行循環內容。