break和continue语句
break和continue語句改變控制流程。break語句在while、for、do/while或switch結構中執行時,使得程序立即退出這些結構,從而執行該結構后面的第一條語句。break語句常用于提前從循環退出或跳過switch結構的其余部分(如圖2.22)。圖2.26演示了for重復結構中的break語句,if結構發現x變為5時執行break,從而終止for語句,程序繼續執行for結構后面的cout語句。循環只執行四次。
注意這個程序中控制變量x在for結構首部之外定義。這是因為我們要在循環體中和循環執行完畢之后使用這個控制變量。
continue語句在while、for或do/while結構中執行時跳過該結構體的其余語句,進入下一輪循環。在while和do/while結構中,循環條件測試在執行continue語句之后立即求值。在for結構中,執行遞增表達式,然后進行循環條件測試。前面曾介紹過.while結構可以在大多數情況下取代for結構。但如果while結構中的遞增表達式在continue語句之后,則會出現例外。這時,在測試循環條件之前沒有執行遞增,并且while與for的執行方式是不同的。圖2.27在for結構中用continue語句跳過該結構的輸出語句,進入下一輪循環。
// Fig.2.26:fig02 26.cpp
// Usinq the break statement in a for structure
#include< ostream.h>
int main()
{
// x declared here so it can be used after the loop
int x;
for ( x = 1; x <= 10; x++ ) {
if { x == 5 )
break; // break loop only if x is 5
cout << x <<" ";
}
cout << " Broke out of loop at x of" << x << endl;
return O;
}
輸出結果:
l 2 3 4
Broke out of loop at x of 5
圖2.26 for重復結構中的break語句
// Fig. 2.27: figO2_OT.cpp
// Using the continue statement in a for structure
#include < iostream.h>
int main()
{
for ( iht x = 1; x <- 10; x++ } {
if {x==5)
continue; // skip remaining code in loop
// only if x is 5
cout << x <<" ";
}
cout << "
Used continue to skip printing the value 5"
<< endl;
return O;
}
l 2 3 4 5 6 7 9 9 10
USed continue to skip printing the value 5
圖 2.27 在for結構用continue語句
編程技巧2.30
有些程序員認為break和continue會破壞結構化編程。由于這些語句可以通過后面要介紹的結構化編程方法實現,因此這些程序員不用break和continue。
性能提示 2.9
正確使用break和continue語句能比后面要介紹的通過結構化編程方法的實現速度更快。
軟件工程視點2.10
達到高質量軟件工程與實現最佳性能軟件之間有一定沖突。通常,要達到一個目標,就要犧牲另一個目標。
2016考研復試技巧http://www.kyjxy.com/fushi/zhinan/
考研專碩備考資料http://www.kyjxy.com/zhuanshuo/
考研院校政策http://www.kyjxy.com/yuanxiao/zhengce/
總結
以上是生活随笔為你收集整理的break和continue语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python画熊猫论文_Python数据
- 下一篇: sap 打印预览界面点击打印时记录打印次