C语言之控制流

来源:互联网 发布:mac地址8个 编辑:程序博客网 时间:2024/04/30 19:11
1、因为if只是简单的测试表达式的数值,所以某些缩短是可以的,
    if (expression)
instead of
    if (expression != 0)

2、It is a good idea to use braces when there are nested ifs.
    当有嵌套的if时,用括号扩起语句是好的主意。

3、switch 语句
    switch (expression)
    {     
          case const-expr:
              statements;
          case const-expr:
              statements;
          default:
              statements;
    }
case的标签(labels)是一个或多个常数整型值或者常数表达式,default是可选择的,case和default的顺序是可以按照任意顺序排列。

4、switch语句中的break用法:break的声明导致从switch中立即退出,因为case仅仅是作为一个label,如果程序在一个case后的code完成后,没有一个明确地退出,那么程序会一直执行下去直到一个明确地退出。在switch中最常用的是break和return,当然break也可以用在循环语句中。

5、case穿透(falling though cases)是一件有利有弊的事情,积极的一面是将多种cases集中起来执行同一个计算,但是在正常的操作过程中需要明确每一个case都要以break结尾防止穿透到下一个case,因为在程序修改的过程中,这是一个不健壮的部分,可能导致崩溃。在case穿透的应用中,应该要保守,且需要做好注释。

6、在最后一个case后面加上break是一个好的习惯,即使在逻辑上不需要,但是当有一天需要修改程序加入case时,这个做法会拯救你。

7、for语句和while语句的等价变换:
    for (expr1; expr2; expr3)
          statement;
等价于
    expr1;
    while (expr2)
    {
          statement;
          expr3;
    }

8、while和for的使用环境
当不需要进行初始化和重初始化的时候,while是最自然的选择;
当有一个简单的初始换和增量时,for是比较好的选择,因为它能把循环控制语句集合在一起且在循环顶部可见。  

9、逗号运算符
逗号运算符最容易在for语句中找到,多个表达式被逗号分开,计算时是从左往右计算,最右端的类型和值作为整个表达式的类型和值。
例如:
#include <stdio.h>

int main()
{
    int a, b, c, d;
    d = (a = 1, b = 2, c = 3);
    printf("%d %d %d %d\n", a, b, c, d);

    return 0;
输出的值是:1 2 3 3
如果不加括号,输出的值是1 2 3 1,因为整个表达式的类型和值没有输出。

10、break和continue的区别
break:cause the innermost enclosing loop or switch to be exited immediately.
continue: cause the next iteration of the enclosing for, while, or do loop to begin. The continue statement applies only to loops, not to switch. A continue inside a switch inside a loop causes the next loop iteration.

break:导致最内层的封闭循环或者switch立刻退出;
continue:导致for,while,或者do循环的下一个循环开始执行。continue只用在循环中,不用在switch中。一个循环中switch中的continue会导 致下一个循环。
#include <stdio.h>

/* test the break and continue */
int main()
{
    int i;
    for (i = 0; i < 10; i++)
    {
        switch(i)
        {
            case 5:
                break;
        }
        printf("%d", i);
    }
    return 0;
}
输出:0 1 2 3 4 5 6 7 8 9
break只是退出了switch,执行了后面的printf

#include <stdio.h>

/* test the break and continue */
int main()
{
    int i;
    for (i = 0; i < 10; i++)
    {
        switch(i)
        {
            case 5:
                continue;
        }
        printf("%d", i);
    }
    return 0;
}
输出:0 1 2 3 4 6 7 8 9
continue直接执行下一个for循环,没有执行printf

11、goto语句尽量不用。
0 0
原创粉丝点击