
關鍵字 goto 用於控制程式執行的順序,使程式直接跳到指定標籤 (lable) 的地方繼續執行。
形式如下

標籤可以是任意的識別字,後面接一個冒號。
舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | goto label_one; |
| 005 | |
| 006 | label_one: |
| 007 | { |
| 008 | std::cout << "Label One" |
| 009 | << std::endl; |
| 010 | goto label_two; |
| 011 | } |
| 012 | |
| 013 | label_two: |
| 014 | { |
| 015 | std::cout << "Label Two" |
| 016 | << std::endl; |
| 017 | goto label_three; |
| 018 | } |
| 019 | |
| 020 | label_three: |
| 021 | { |
| 022 | std::cout << "Label Three" |
| 023 | << std::endl; |
| 024 | } |
| 025 | |
| 026 | return 0; |
| 027 | } |
| 028 | |
| 029 | /* Kaiching Chang |
| 030 | u0509_2.cpp |
| 031 | 2014-02 */ |
編譯後執行,結果如下
| $ g++ u0509_1.cpp |
| $ ./a.out |
| Label One |
| Label Two |
| Label Three |
| $ |
此例按標籤的順序,在每個標籤下方都用大括弧圍住一個程式區塊, goto 到了指定標籤,就會執行標籤下方的程式區塊
| 006 | label_one: |
| 007 | { |
| 008 | std::cout << "Label One" |
| 009 | << std::endl; |
| 010 | goto label_two; |
| 011 | } |
概念滿簡單的,上面利用標籤順序執行,下面我們另舉一個例子,使 goto 具有迴圈的效果
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | int i = 1; |
| 005 | if (i < 10) { |
| 006 | goto label_one; |
| 007 | } |
| 008 | |
| 009 | label_one: |
| 010 | { |
| 011 | std::cout << "Label One" |
| 012 | << std::endl; |
| 013 | goto label_three; |
| 014 | } |
| 015 | |
| 016 | label_two: |
| 017 | { |
| 018 | std::cout << "Label Two" |
| 019 | << std::endl; |
| 020 | } |
| 021 | |
| 022 | label_three: |
| 023 | { |
| 024 | std::cout << "Label Three" |
| 025 | << std::endl; |
| 026 | i++; |
| 027 | if (i < 10) { |
| 028 | goto label_two; |
| 029 | } |
| 030 | } |
| 031 | |
| 032 | return 0; |
| 033 | } |
| 034 | |
| 035 | /* Kaiching Chang |
| 036 | u0509_2.cpp |
| 037 | 2014-02 */ |
編譯後執行,結果如下
| $ g++ u0509_2.cpp |
| $ ./a.out |
| Label One |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| Label Two |
| Label Three |
| $ |
continue ...
沒有留言:
張貼留言