看板 C_and_CPP 關於我們 聯絡資訊
#include <iostream> #include <cstdlib> using namespace std; int main() { int a[10]; for(int i=0; i<10; i++) { a[i]=i; } int j=0; do{ cout << a[j] << endl; }while(j<10 && a[j++] !=5); return 0; } 我的理解如下: j=0, cout a[0]. 0 < 10 且 a[1] !=5, 所以 cout a[1]. . . . . . . j=4, cout a[4]. 4 < 10 且 a[5] == 5, 所以最終只輸出到4. 但顯然我的想法有誤,最終輸出到5。 我哪裡弄錯了哩? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.33.55.128
james732:我覺得你誤會的是 j++ 這個動作,改成 ++j 就印到 4 了 11/11 23:04
eagle32:謝謝,了解了! 11/11 23:07
world9918:問一下 這個while條件式算是未定義行為嗎? 11/11 23:28
james732:應該沒有問題,因為 && 是 Sequence point 11/11 23:33
james732:j < 10 一定會先做完,才會做 a[j++] !=5 11/11 23:33
Zephyr750:for loop、while都是先檢查條件,後執行內容。 11/12 00:10
Zephyr750:所以執行了 i[0]=0...i[9]=9 11/12 00:11
Zephyr750:do-while loop是先執行,再判斷是否繼續。 11/12 00:11
Zephyr750:所以執行了 cout << a[0] ...(中略)... a[4] << end; 11/12 00:12
Zephyr750:在這時,j=4,進入判斷j++成為了5,所以跳出來。 11/12 00:13
Zephyr750:j++ = ++j,但是在遇到等號似乎就變調。^^ 11/12 00:18
world9918:謝謝4F解答我的問題 11/12 00:43
james732:Sequence point 這個詞也是在板上才學會的...XD 11/12 00:44