精華區beta Programming 關於我們 聯絡資訊
※ 引述《khoguan (Khoguan Phuann)》之銘言: : 至於下述寫法就不 portable: : int i = 0; : cout << i << ' ' << i++; // 不同機器有不同結果,但並不違反標準 我這樣說不妥當,這種寫法不僅不 portable,根本就是 undefined cout << i << ' ' << i++ 是一個而且僅有一個 full expression, 其 sequence point 只出現在這整個 full expression 結束的地方。據之前引用的連結 所提到的C++標準中的規定: "the value of a scalar object may be modified no more than once between any two consecutive sequence points. If it is modified, use of the prior value is restricted and may only be used in determining what new value is to be stored. These requirements must be met for all possible orders in which a full-expression's subexpressions may be evaluated. Failure to meet all of these requirements results in "undefined" behavior" 不但 cout << i << i++ 是 undefined a[i] = ++i; 或是 i = ++i; 這些看起來很清純無辜的寫法都是 undefined. undefined behavior 是寫程式時務必要避免的。即使能編、能跑、能得到所要的結果都不 該這麼寫。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.208.168