zoukankan      html  css  js  c++  java
  • 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("哈哈
    ");
     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("哈哈
    ");
     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循环。

    人生之路,不忘初心,勿忘始终!
  • 相关阅读:
    python常见错误
    接口自动化常用断言方法python
    Mysql2docx自动生成数据库说明文档
    常用的实用小工具
    移动App专项测试
    AndroidStudio 快捷键(最实用的20个)(转)
    Linux常用命令大全(非常全!!!)(转)
    Fiddler使用教程(转)
    Subversion Edge
    杂点
  • 原文地址:https://www.cnblogs.com/xdl745464047/p/4003460.html
Copyright © 2011-2022 走看看