Re: [問題] 請問優先「計算」的問題
※ 引述《loteslogin (張三立)》之銘言:
: 以下面這個算式來說:
: return ((a+=5) > 9) ? a+2 : a+4;
: 以「結合」的優先順序當然是 a+= 還有 + 會優先結合,
: 但是以「計算」的優先順序來說,
: 不知道標準 C/C++ 是否有規定關於這個式子在計算上的優先順序呢?
C++ standard 裡有規定 conditional operator 第一個 exporession 的
side effect(不含 temporary object destruction)會發生在第二與第三個
expression 求值之前。第二與第三個 expression 只有其中一個會被求值(depends
on first expression)。
請見
ISO/IEC 14882, 2003
5.16 Conditional operator
一節。
節錄一小段於此:(如果此舉是違法的,請告知在下刪除,謝謝)
Conditional expressions group right-to-left. The first expression is
implicitly converted to bool (clause 4). It is evaluated and if it is true,
the result of the conditional expression is the value of the second
expression, otherwise that of the third expression. All side effects of the
first expression except for destruction of temporaries (12.2) happen before
the second or third expression is evaluated. Only one of the second and
third expressions is evaluated.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.173.134.87
※ 編輯: sbrhsieh 來自: 218.173.134.87 (04/01 16:25)
推
04/01 18:29, , 1F
04/01 18:29, 1F
推
04/01 19:16, , 2F
04/01 19:16, 2F
推
04/01 20:30, , 3F
04/01 20:30, 3F
推
04/02 15:48, , 4F
04/02 15:48, 4F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章