重複執行 語句,直到條件變成 false 為止。 如需範圍型for語句的資訊,請參閱範圍型for語句 (C++)。 如需 C++/CLI for each 語句的相關信息,請參閱 for each。 in
語法
for (init-expression;cond-expression;loop-expression)
statement
備註
for使用語句來建構必須執行指定次數的迴圈。
語句 for 包含三個選擇性部分,如下表所示。
for 循環專案
| 語法名稱 | 執行時 | 說明 |
|---|---|---|
init-expression |
在語句的任何其他元素 for 之前, init-expression 只會執行一次。 控制項接著會傳遞至 cond-expression。 |
通常用來初始化迴圈索引。 它可以包含表達式或宣告。 |
cond-expression |
執行的每個反覆 statement專案之前,包括第一個反覆專案。
statement 只有在 cond-expression 評估為 true 時才會執行 (非零)。 |
評估為整數型別的表達式,或具有明確轉換成整數型別的類別型別。 通常用來測試迴圈終止準則。 |
loop-expression |
在每個反覆 statement項目結束時。 執行之後 loop-expression , cond-expression 會進行評估。 |
通常用來遞增迴圈索引。 |
下列範例顯示使用 for 語句的不同方式。
#include <iostream>
using namespace std;
int main() {
// The counter variable can be declared in the init-expression.
for (int i = 0; i < 2; i++ ){
cout << i;
}
// Output: 01
// The counter variable can be declared outside the for loop.
int i;
for (i = 0; i < 2; i++){
cout << i;
}
// Output: 01
// These for loops are the equivalent of a while loop.
i = 0;
while (i < 2){
cout << i++;
}
// Output: 01
}
init-expression 和 loop-expression 可以包含以逗號分隔的多個語句。 例如:
#include <iostream>
using namespace std;
int main(){
int i, j;
for ( i = 5, j = 10 ; i + j < 20; i++, j++ ) {
cout << "i + j = " << (i + j) << '\n';
}
}
/* Output:
i + j = 15
i + j = 17
i + j = 19
*/
loop-expression 可以遞增或遞減,或以其他方式修改。
#include <iostream>
using namespace std;
int main(){
for (int i = 10; i > 0; i--) {
cout << i << ' ';
}
// Output: 10 9 8 7 6 5 4 3 2 1
for (int i = 10; i < 20; i = i+2) {
cout << i << ' ';
}
}
// Output: 10 12 14 16 18
當 for 內的 、傳回或 (傳回或 goto 至迴圈外部標記的for語句)statement執行時break,迴圈就會終止。
continue迴圈中的 for 語句只會終止目前的反覆專案。
如果cond-expression省略,則會將其視為 true,而且for迴圈不會在沒有 、 return或 goto 的情況下statement終止break。
雖然 語句的三個 for 字段通常用於初始化、測試終止和遞增,但它們不限於這些用途。 例如,下列程式代碼會列印數位 0 到 4。 在此情況下, statement 是 null 語句:
#include <iostream>
using namespace std;
int main()
{
int i;
for( i = 0; i < 5; cout << i << '\n', i++){
;
}
}
for 迴圈和 C++ Standard
C++標準表示,迴圈中宣告的 for 變數在迴圈結束之後 for 應該超出範圍。 例如:
for (int i = 0 ; i < 5 ; i++) {
// do something
}
// i is now out of scope under /Za or /Zc:forScope
根據預設,在下 /Ze,迴圈中 for 宣告的變數會保留在範圍內,直到 for 迴圈的封入範圍結束為止。
/Zc:forScope 會啟用在 for 迴圈中宣告之變數的標準行為,而不需要指定 /Za。
您也可以使用 循環的範圍 for 差異來重新宣告下方 /Ze 的變數,如下所示:
// for_statement5.cpp
int main(){
int i = 0; // hidden by var with same name declared in for loop
for ( int i = 0 ; i < 3; i++ ) {}
for ( int i = 0 ; i < 3; i++ ) {}
}
此行為更緊密地模擬迴圈中宣告之變數的標準行為,這需要迴圈中forfor宣告的變數在完成迴圈之後超出範圍。 在迴圈中 for 宣告變數時,編譯程式會在內部將它升階為迴圈封入範圍的局部變數 for 。 即使已經有具有相同名稱的局部變數,也會升級它。
另請參閱
反覆運算陳述式
關鍵字
while 語句 (C++)
do-while 語句 (C++)
範圍型 for 語句 (C++)