return 語句
終止函數的執行并返回對調用函數的控制(或對操作系統的控制,如果您從 main 函數轉移控制)。緊接在調用之后在調用函數中恢復執行。
語法
return [expression];
備注
expression 子句(如果存在)將轉換為函數聲明中指定的類型,就像正在執行初始化一樣。從該類型的表達式到 return 類型的函數的轉換會創建臨時對象。
expression 子句的值將返回調用函數。如果省略該表達式,則函數的返回值是不確定的。構造函數和析構函數以及類型為 void的函數無法在 return 語句中指定表達式。所有其他類型的函數必須在 return 語句中指定表達式。
當控制流退出封閉函數定義的塊時,結果將與執行不帶表達式的 return 語句所獲得的結果一樣。這對于聲明為返回值的函數無效。
一個函數可以包含任意數量的 return 語句。
以下示例將一個表達式與 return 語句一起使用來獲取兩個整數中的最大者。
// return_statement2.cpp#include <stdio.h>int max ( int a, int b ){ return ( a > b ? a : b );}int main(){ int nOne = 5; int nTwo = 7; printf_s("/n%d is bigger/n", max( nOne, nTwo ));}
goto 語句
goto 語句無條件地將控制權轉移給由指定的標識符標記的語句。
語法
goto identifier;
備注
由 identifier 指定的標記語句必須位于當前函數中。所有 identifier 名稱都是內部命名空間的成員,因此不會干擾其他標識符。
語句標簽僅對 goto 語句有意義;其它情況下,語句標簽將被忽略。不能重新聲明標簽。
盡可能使用 break、continue 和 return 語句而不是 goto 語句是一種好的編程風格。但是,因為 break 語句僅退出循環的一個級別,所以可能必須使用 goto 語句退出深度嵌套的循環。
在此示例中,當 i 等于 3 時,goto 語句將控制權轉移給標記為 stop 的點。
// goto_statement.cpp#include <stdio.h>int main(){ int i, j; for ( i = 0; i < 10; i++ ) { printf_s( "Outer loop executing. i = %d/n", i ); for ( j = 0; j < 2; j++ ) { printf_s( " Inner loop executing. j = %d/n", j ); if ( i == 3 ) goto stop; } } // This message does not print: printf_s( "Loop exited. i = %d/n", i ); stop: printf_s( "Jumped to stop. i = %d/n", i );}
輸出:
正在執行外部循環。i = 0 正在執行內部循環。j = 0 正在執行內部循環。j = 1正在執行外部循環。i = 1 正在執行內部循環。j = 0 正在執行內部循環。j = 1正在執行外部循環。i = 2 正在執行內部循環。j = 0 正在執行內部循環。j = 1正在執行外部循環。i = 3 正在執行內部循環。j = 0跳轉以停止。i = 3
控制的轉移
可以在 goto 語句中使用 語句或 switchcase 標簽來指定分支超出初始值設定項的程序。此類代碼是非法的,除非包含初始值設定項的聲明在跳轉語句發生的塊所封閉的塊中。
下面的示例顯示了聲明和初始化對象 total、ch 和 i 的循環。也存在將控制權傳遞過初始值設定項的錯誤 goto 語句。
// transfers_of_control.cpp// compile with: /W1// Read input until a nonnumeric character is entered.int main(){ char MyArray[5] = {'2','2','a','c'}; int i = 0; while( 1 ) { int total = 0; char ch = MyArray[i++]; if ( ch >= '0' && ch <= '9' ) { goto Label1; int i = ch - '0'; Label1: total += i; // C4700: transfers past initialization of i. } // i would be destroyed here if goto error were not present else // Break statement transfers control out of loop, // destroying total and ch. break; }}
在前面的示例中,goto 語句嘗試將控制權傳遞過 i 的初始化。但是,如果已聲明但未初始化 i,則該傳遞是合法的。
在用作 total 語句的 chstatement 的塊中聲明的對象 和 while 在使用 break 語句退出此塊時將被銷毀。