2

【C进阶】7、循环语句

 3 years ago
source link: https://segmentfault.com/a/1190000040556180
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Summary

1)do...while语句先执行后判断,循环体至少执行一次;while语句先判断后执行,循环体可能不执行;for语句先判断后执行,相比while更简洁(因为for的一行里包括了循环变量初始化条件判断修改循环变量三个要素)。

2)break和continue的区别:

  • break表示终止循环的执行
  • continue表示终止本次循环,进入下次循环执行

循环语句的基本工作方式:

  • 通过条件表达式判断是否执行循环体
  • 条件表达式遵循if语句表达式的原则

1、do ... while

2、while

image.png

3、for

image.png

4、do... while示例

使用do while(0);配合break语句,实现对动态申请内存的释放。

int func(int n)
{
    int i = 0;
    int ret = 0;
    int* p = (int*)malloc(sizeof(int) * n);
    
    do
    {
        if(NULL == p) break;
        
        if(n < 5) break;
        
        if(n > 100) break;
        
        for(i = 0; i<n; i++)
        {
            p[i] = i;
            printf("%d\n", p[i]);
        }
        ret = 1;
    } while(0);
    
    free(p);
    
    return ret;
}

本文总结自“狄泰软件学院”唐佐林老师《C语言进阶课程》。
如有错漏之处,恳请指正。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK