学习一下 for 循环的几种不同方式,了解一下原理及差异
完整的测试代码参考 GitHub :for 循环测试代码
1 常用形态
对于 for 循环来说,最常用的形态如下
for (表达式1; 表达式2; 表达式3)
{// code
}
流程图如下:
编写测试代码如下
void forMethod1()
{cout << "\nThis is i++ test start" << endl;#if 0for (int i = 0; i < MAX; i++){cout << "for start i = " << i << endl;cout << "for test" << endl;cout << "for end i = " << i << endl;}
#elseint i; // 循环变量声明放for循环之前,便于查看循环结束后的循环变量值for (i = 0; i < MAX; i++){cout << "for start i = " << i << endl;cout << "for test" << endl;cout << "for end i = " << i << endl;}// 此时循环变量已是最后一次修改后的,但不满足循环条件的值cout << "for exit, i = " << i << endl;
#endifcout << "This is i++ test end\n" << endl;
}
上述代码执行结果如下
This is i++ test start
for start i = 0
for test
for end i = 0
for start i = 1
for test
for end i = 1
for start i = 2
for test
for end i = 2
for start i = 3
for test
for end i = 3
for start i = 4
for test
for end i = 4
for exit, i = 5
This is i++ test end
从执行结果来看,在退出 for 循环代码块后,i 的值是 5 ,按流程图也就是在经过了最后一次循环变量自增,再去判断循环条件是否满足,此时不满足 i < 5 ,随后退出 for 循环。
2 代码块中修改循环变量
另一种比较常用的方式,就是在代码块中修改循环变量,以实现不同的循环方式。
测试代码如下
void forMethod3()
{cout << "\nThis is i++ test V2 start" << endl;int i;for (i = 0; i < MAX;){cout << "for start i = " << i << endl;cout << "for test, start i++" << endl;// 循环体内执行改变循环变量操作,实现不同循环效果i++;cout << "for end i = " << i << endl;}cout << "for exit, i = " << i << endl;cout << "This is i++ test V2 end\n" << endl;
}
代码实际运行结果如下
This is i++ test V2 start
for start i = 0
for test, start i++
for end i = 1
for start i = 1
for test, start i++
for end i = 2
for start i = 2
for test, start i++
for end i = 3
for start i = 3
for test, start i++
for end i = 4
for start i = 4
for test, start i++
for end i = 5
for exit, i = 5
This is i++ test V2 end
此中方式,区别在于将改变循环变量操作放进代码块内执行,以实现不同循环方式,比如
// 步长为1
i = i + 1;
i += 1;
i++;
++i;// 步长为2
i = i + 2;
i += 2;...