Try   HackMD
tags: tgirc早修book

break、continue

break

當達到一個條件時,我們不希望某段指令持續運作,此時就可以用 break 離開程式碼

範例 1

#include <iostream> using namespace std; int main(){ int i=0; while(true){ if(i==37){ cout<<i<<" !!! ouob\n"; break; } cout<<i<<" onoq\n"; i++; } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

只要迴圈是 true,這段迴圈就會一直不間斷的執行下去,當 i 是 37 時,就會輸出 37 !!! ouob 再跳出迴圈

運用 break 的結果,相較於讓程式全部跑完再執行指令來的有效率不少,是相當常用的指令,一般會用於 switch 或是迴圈,在其他地方使用可能會造成錯誤

continue

continue 通常用於迴圈中,在其他地方使用可能會造成編譯錯誤,執行 continue 時 C++ 會馬上跳回迴圈的開頭然後再繼續執行,而不執行在 continue 後的程式碼

範例 1

#include <iostream> using namespace std; int main(){ int i=0; while(true){ if(i<37){ cout<<i<<" onoq\n"; i++; continue; cout<<"no cout QQ\n"; } else if(i==37){ cout<<i<<" !!! ouob\n"; i++; break; } } return 0; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →