C中的side effect 和 sequence point
wiki 中 sequence point 定義:
A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that allside effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions. Adding one or more sequence points is one method of ensuring a consistent result, because this restricts the possible orders of evaluation.
簡單的說就是在C/C++中有一些執(zhí)行順序問題,C/C++定義了一些sequence point,在下一個sequence point 執(zhí)行之前必須把前一個執(zhí)行完,但是問題是在一個sequence point 和另一個之間還有一些side effect。由于這些就引出一些有趣的問題。條件運算符?:、逗號運算符、邏輯與&&、邏輯或||的每一個操作數(shù)求值之后是Sequence Point。
問題一:
問題二:
問題三:
問題四:
所以我們要堅持的原則是:在兩個Sequence Point之間,同一個變量的值只允許被改變一次。
A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that allside effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions. Adding one or more sequence points is one method of ensuring a consistent result, because this restricts the possible orders of evaluation.
簡單的說就是在C/C++中有一些執(zhí)行順序問題,C/C++定義了一些sequence point,在下一個sequence point 執(zhí)行之前必須把前一個執(zhí)行完,但是問題是在一個sequence point 和另一個之間還有一些side effect。由于這些就引出一些有趣的問題。條件運算符?:、逗號運算符、邏輯與&&、邏輯或||的每一個操作數(shù)求值之后是Sequence Point。
問題一:
f(g( ), h( ) );
先執(zhí)行誰?答:g( ),h( ) 的順序不確定,它們執(zhí)行之后才執(zhí)行f ( );問題二:
int i = 1;i = i ++;
結果是? 答:undefined,因為我們知道i++ 是先返回再改變i的值的,那么賦值語句右邊就有了值了,那么就存在這樣的兩種情況:1,i先賦值,再++,那么i現(xiàn)在為2;2,先++,然后賦值,注意此時賦值的內容是還沒++的值,所以i為1;根據(jù)不同的編譯器會得出不同的結果的。問題三:
int a = 1; a = (++a)+(++a)+(++a);
結果是?答:undefined,這個的問題是,到底是先把每個++執(zhí)行完之后才進行加法還是先把前兩個先加再執(zhí)行最后一個++?兩者的答案分別是9,11。當然還有其他情況。問題四:
int i = 1; int a[10]={0}; a[i++] = i;
答:同問題2.所以我們要堅持的原則是:在兩個Sequence Point之間,同一個變量的值只允許被改變一次。
posted on 2011-11-14 15:08 is-programmer 閱讀(351) 評論(0) 編輯 收藏 引用 所屬分類: C/C++