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結構首部以外定義。這是由於咱們要在循環體中和循環執行完畢以後使用這個控制變量。ios

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 4oop

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 << "\nUsed continue to skip printing the value 5"
             << endl;
      return O;
 }

l 2 3 4 5 6 7 9 9 10spa

USed continue to skip printing the value 5code

圖 2.27 在for結構用continue語句ip

編程技巧2.30

有些程序員認爲break和continue會破壞結構化編程。因爲這些語句能夠經過後面要介紹的結構化編程方法實現,所以這些程序員不用break和continue。rem

性能提示 2.9

正確使用break和continue語句能比後面要介紹的經過結構化編程方法的實現速度更快。

軟件工程視點2.10

達到高質量軟件工程與實現最佳性能軟件之間有必定衝突。一般,要達到一個目標,就要犧牲另外一個目標。

2016考研複試技巧http://www.kyjxy.com/fushi/zhinan/
考研專碩備考資料http://www.kyjxy.com/zhuanshuo/
考研院校政策http://www.kyjxy.com/yuanxiao/zhengce/

相關文章
相關標籤/搜索