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.
簡(jiǎn)單的說(shuō)就是在C/C++中有一些執(zhí)行順序問(wèn)題,C/C++定義了一些sequence point,在下一個(gè)sequence point 執(zhí)行之前必須把前一個(gè)執(zhí)行完,但是問(wèn)題是在一個(gè)sequence point 和另一個(gè)之間還有一些side effect。由于這些就引出一些有趣的問(wèn)題。條件運(yùn)算符?:、逗號(hào)運(yùn)算符、邏輯與&&、邏輯或||的每一個(gè)操作數(shù)求值之后是Sequence Point。
問(wèn)題一:
f(g( ), h( ) );
先執(zhí)行誰(shuí)?答:g( ),h( ) 的順序不確定,它們執(zhí)行之后才執(zhí)行f ( );
問(wèn)題二:
int i = 1;i = i ++;
結(jié)果是? 答:undefined,因?yàn)槲覀冎纈++ 是先返回再改變i的值的,那么賦值語(yǔ)句右邊就有了值了,那么就存在這樣的兩種情況:1,i先賦值,再++,那么i現(xiàn)在為2;2,先++,然后賦值,注意此時(shí)賦值的內(nèi)容是還沒(méi)++的值,所以i為1;根據(jù)不同的編譯器會(huì)得出不同的結(jié)果的。
問(wèn)題三:
int a = 1; a = (++a)+(++a)+(++a);
結(jié)果是?答:undefined,這個(gè)的問(wèn)題是,到底是先把每個(gè)++執(zhí)行完之后才進(jìn)行加法還是先把前兩個(gè)先加再執(zhí)行最后一個(gè)++??jī)烧叩拇鸢阜謩e是9,11。當(dāng)然還有其他情況。
問(wèn)題四:
int i = 1; int a[10]={0}; a[i++] = i;
答:同問(wèn)題2.
所以我們要堅(jiān)持的原則是:在兩個(gè)Sequence Point之間,同一個(gè)變量的值只允許被改變一次。