Re: [問題] 同一行程式碼變更變數兩次
: sum = sub_Function_a ( max ) + sub_Function_b ( max++ );
借這篇文章,提出我對「Sequence Point」一直以來的疑問,真心跪求知識帝解惑。
之前看這篇文章:http://en.wikipedia.org/wiki/Sequence_point
裡面提到在 C/C++ 的 Sequence Point (順序點) 中,有一個順序點是
「Before a function is entered in a function call.」
在微軟 MSDN 的文章中:http://msdn.microsoft.com/en-us/library/d45c7a5d.aspx
亦指出函數呼叫本身是個順序點。
「Function-call operator.
The function-call expression and all arguments to a function,
including default arguments, are evaluated and all side effects
completed prior to entry to the function.」
又「相加運算子+」的運算優先權高於「指派運算子=」,所以只剩下決定,要先呼叫
sub_Function_a(max) 還是先呼叫 sub_Function_b(max++)。誰先被呼叫,對於結果當然
是有差別的。
但我以為這個部份應該不是未定義的,應該一定是先呼叫 sub_Function_a(max) 吧?
因為看這篇:http://msdn.microsoft.com/en-us/library/yck2zaey.aspx
講解運算優先順序。
該文的圖1 舉「cout << a+b*c << "\n";」做為解說例子。
當 a+b*c 的運算做完,假設是 5566 好了,其運算就變成「cout << 5566 << "\n";」
然後該文章說
「Left shift (<<) has the lowest precedence in the expression, but
there are two occurrences. Because the left-shift operator groups
left-to-right, the left subexpression is evaluated first and then
the right one.」
因為 << 這個二元運算子是左結合性,所以先執行「cout << 5566」,那原文的
sub_Function_a ( max ) + sub_Function_b ( max++ ) 運算,其中 function call
運算子的優先權最高,一定要先執行函數呼叫。又 function call 在 MSDN 也是寫他
結合性為由左到右:http://msdn.microsoft.com/en-us/library/126fe14k.aspx
所以我才認為,應該 sub_Function_a(max) 會先執行,而不是未定義,
但 gcc 是會給警告訊息,而且 wiki 的網頁裡面也說,函數執行順序不一定
「However, it is not specified in which order
f(), g(), h() are executed.」
有修過編譯器的課程,但是沒吸收到多少,
求解惑,感謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 124.8.128.171
→
10/13 18:14, , 1F
10/13 18:14, 1F
→
10/13 18:15, , 2F
10/13 18:15, 2F
→
10/13 18:15, , 3F
10/13 18:15, 3F
→
10/13 18:16, , 4F
10/13 18:16, 4F
→
10/13 18:17, , 5F
10/13 18:17, 5F
→
10/13 18:18, , 6F
10/13 18:18, 6F
→
10/13 18:19, , 7F
10/13 18:19, 7F
→
10/13 18:19, , 8F
10/13 18:19, 8F
→
10/13 18:20, , 9F
10/13 18:20, 9F
→
10/13 18:21, , 10F
10/13 18:21, 10F
→
10/13 18:21, , 11F
10/13 18:21, 11F
→
10/13 18:21, , 12F
10/13 18:21, 12F
→
10/13 18:23, , 13F
10/13 18:23, 13F
→
10/13 18:23, , 14F
10/13 18:23, 14F
→
10/13 18:24, , 15F
10/13 18:24, 15F
推
10/13 18:38, , 16F
10/13 18:38, 16F
→
10/13 18:39, , 17F
10/13 18:39, 17F
推
10/13 18:43, , 18F
10/13 18:43, 18F
→
10/13 18:47, , 19F
10/13 18:47, 19F
→
10/13 18:57, , 20F
10/13 18:57, 20F
→
10/13 18:58, , 21F
10/13 18:58, 21F
推
10/13 19:07, , 22F
10/13 19:07, 22F
→
10/13 19:08, , 23F
10/13 19:08, 23F
→
10/13 19:08, , 24F
10/13 19:08, 24F
→
10/13 19:09, , 25F
10/13 19:09, 25F
→
10/13 19:10, , 26F
10/13 19:10, 26F
→
10/13 19:10, , 27F
10/13 19:10, 27F
→
10/13 19:17, , 28F
10/13 19:17, 28F
推
10/13 19:36, , 29F
10/13 19:36, 29F
→
10/13 19:40, , 30F
10/13 19:40, 30F
→
10/13 19:41, , 31F
10/13 19:41, 31F
→
10/13 19:41, , 32F
10/13 19:41, 32F
→
10/13 21:16, , 33F
10/13 21:16, 33F
→
10/13 21:17, , 34F
10/13 21:17, 34F
→
10/13 22:16, , 35F
10/13 22:16, 35F
→
10/13 22:16, , 36F
10/13 22:16, 36F
討論串 (同標題文章)