goto
令程式的執行流程跳到一個被標記的位置。
語法
label:
goto label; // 將程式的執行流程跳到 label 處
提醒
一般來說在C語言的教科書中,使用goto被認為是一個非常糟糕的事情,甚至被認為永遠不該出現,但是如果運用得宜,則可以讓某些程式變得簡潔;而goto在許多的程式設計人員間不受歡迎的原因,是因為如果在goto的使用上不夠拘謹,很容易產生非預期的程式執行流程,甚至導致程式無法進行除錯。
基於以上所述,以一個多層巢狀迴圈為例子,用if判斷當某個條件成立後就必須跳出整個巢狀迴圈,在此使用goto可以讓編寫程式碼更為便利、簡單。
範例
for(byte r = 0; r < 255; r++){ for(byte g = 255; g > -1; g--){ for(byte b = 0; b < 255; b++){ if (analogRead(0) > 250){ goto bailout;} // more statements ... } } } bailout:
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.