C語言之控制流

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語句儘量不用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章