for (a = 1; a < 10; a++)
for (b = 1; b < 10; b++)
printf("%d %d\n", a, b);
a = 1; b = 1;
while (a < 10) {
while (b < 10) { // b 只初始化一次!
printf("%d %d\n", a, b);
b++;
}
a++;
}
結果:外層 a=1 時,內層 b 跑 1→9。外層 a=2 時,b 已為 10,內層 while(b<10) 直接跳過,**後續外層迴圈完全不執行內層**。
a = 1;
while (a < 10) {
b = 1; // 【關鍵】每進入外層一次,內層計數器歸零/重置
while (b < 10) {
printf("%d %d\n", a, b);
b++;
}
a++;
}
| for 結構 | 等價 while 結構 |
|---|---|
for (init; cond; update) {
body;
}
|
init;
while (cond) {
body;
update;
}
|
for (i=0; i |
i = 0;
while (i < n) {
j = 0; // 內層初始化在外層體內!
while (j < m) {
body;
j++;
}
i++;
}
|
i++)。for (int i=0; ...),i 迴圈外不可見,減少汙染。while(fgets(buf, n, fp)))。break/continue)。巢狀迴圈轉換鐵律:內層初始化/重置語句必須移至外層迴圈體內部。這是 for 自動語義 (每輪進入隱含重置) 與 while 手動語義的核心差異。養成「寫 while 先想:哪些變數要在每輪重置?」的習慣。