一般說來,程式進入迴圈體後在下次迴圈判斷之前執行迴圈體裡的所有語句,break和continue語句可以終止迴圈或忽略某些迴圈。
break:此語句導致程式終止包含它的迴圈,並進行程式的下一階段(整個迴圈後面的語句),即,不是跳到下乙個迴圈週期而是退出迴圈。如果break語句包含在巢狀迴圈裡,它只跳出最裡面的迴圈。
[cpp]view plain
copy
#include
intmain()
printf("now i = %d\n"
,i);
} printf("test over !!!\n"
);
return
0;
}
[plain]view plain
copy
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now i = 0
start...
now i = 1
start...
now i = 2
start...
break
test over !!!
$
巢狀迴圈(break)
:[cpp]view plain
copy
#include
intmain()
printf("now n= %d\n"
,n);
} if
(i==3)
printf("now i = %d\n"
,i);
} printf("test over !!!\n"
);
return
0;
}
[plain]view plain
copy
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now n= 0
now n= 1
now n= 2
break
now i = 0
start...
now n= 0
now n= 1
now n= 2
break
now i = 1
start...
now n= 0
now n= 1
now n= 2
break
now i = 2
start...
now n= 0
now n= 1
now n= 2
break
break
test over !!!
$
continue:
迴圈語句裡有此語句時,程式執行到此語句時,不在執行迴圈體裡continue後面的語句而是跳到下乙個迴圈入口處執行下乙個迴圈。如果continue語句包含在巢狀迴圈語句裡,它只影響包含它的最裡層的迴圈。
[cpp]view plain
copy
#include
intmain()
printf("now i = %d\n"
,i);
} printf("test over !!!\n"
);
return
0;
}
[plain]view plain
copy
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now i = 0
start...
now i = 1
start...
now i = 2
start...
continue
start...
now i = 4
start...
now i = 5
test over !!!
$
巢狀迴圈(continue):
[cpp]view plain
copy
#include
intmain()
printf("now n= %d\n"
,n);
} if
(i==3)
printf("now i = %d\n"
,i);
} printf("test over !!!\n"
);
return
0;
}
[plain]view plain
copy
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 0
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 1
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 2
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
continue
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 4
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 5
test over !!!
$
break與continue的區別
本文主要講述一下break關鍵字與continue關鍵字用法的區別 break關鍵字很重要,表示終止本層迴圈。這是沒加break之前的,它的輸出結果是0,1,2,3,4,5,6,7,8,9。加上break以後,它的輸出結果是0,1,2,3 輸出的結果變成了0,1,2,3,5,6,7,8,9 cont...
break 與 continue 的區別
最近在做一些題目,經常要用到break 與 continue,有些題目也稀里糊塗地做對了,自己也覺得會了,但是並沒有深入去了解,今天終於意識到這種情況的危險性了,越是浮在水面上,越無法把握事物的本質,題目就這麼稀里糊塗地過了,不僅浪費了時間,更為以後的解題留下了隱患,學習還是要踏踏實實的,一步乙個腳...
break與continue的區別
break 用於永久終止迴圈。即不執行本次迴圈中break後面的語句,直接結束迴圈。不迴圈了 continue 用於終止本次迴圈。即本次迴圈中continue後面的 不執行,開始進行下一次迴圈。還在迴圈 對於break而言,通俗來講就是,在迴圈中,i 0,進入for的迴圈體,輸出 哈哈 後,遇到 b...