08-for循环和while循环的小区别

直接看例子:

whie循环

 1 #include <stdio.h>
 2 
 3 int main(int argc, const char * argv[])
 4 {
 5     int count = 0;//count定义在while循环外部,作用域范围不局限在while循环
 6     while(count < 5)
 7     {
 8         printf("哈哈\n");
 9         count++;
10     }
11     return 0;
12 }

for循环

 1 #include <stdio.h>
 2 
 3 int main(int argc, const char * argv[])
 4 {
 5 
 6     for(int count = 0; count < 5; count++)//count定义在for循环内部,作用域就是for循环代码块
 7     {
 8         printf("哈哈\n");
 9     }
10     return 0;
11 }

分析:

(1) while循环和for循环都实现了相同的功能。

(2)区别:

  1> while循环中,循环变量count只能定义在while循环外部,因此count的作用域不局限在while内部,当循环执行完毕后,循环体在内存中释放,而count仍存在内存中,占用内存。

  2> for循环中,循环变量count定义在for循环内部,因此count的作用域就是for循环的代码块,当循环执行完毕后,会随着整个循环体在内存中释放,不占用内存资源。

综上:for循环比while循环更加优化(节约内存),以后能使用for循环尽量使用for循环。

posted @ 2014-10-01 19:03  微雨独行  阅读(224)  评论(0编辑  收藏  举报
1 2