易采站长站为您分析解析C++中的for循环以及基于范围的for语句使用,是C++入门学习中的基础知识,需要的朋友可以参考下
for循环语句
重复执行语句,直到条件变为 false。
语法
for ( init-expression ; cond-expression ; loop-expression )
statement;
备注
使用 for 语句可构建必须执行指定次数的循环。
for 语句包括三个可选部分,如下表所示。
for 循环元素
下面的示例将显示使用 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: 012
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
当 statement 中的 break、return 或 goto(转到 for 循环外部的标记语句)执行时,for 循环将终止。 for 循环中的 continue 语句仅终止当前迭代。
如果忽略 cond-expression,则认为其为 true,for 循环在 statement 中没有 break、return 或 goto 时不会终止。
虽然 for 语句的三个字段通常用于初始化、测试终止条件和递增,但并不限于这些用途。例如,下面的代码将打印数字 0 至 4。在这种情况下,statement 是 null 语句:











