作者bluesapphire (Blue Sapphire)
看板ask
標題[請問] C for loop 有辦法同時宣告和 assign 嗎?
時間Wed Sep 4 00:55:55 2024
各位大大好
我想問一下
以下的 code, 我發現 max 打印出來會是 0 (而不是我腦海預期的 5566)
請問一下,我要怎麼在 for loop 那邊,同時宣告 int idx, 以及 assign 值給 max 呢?
(從實驗結果推估,for loop 的 max 因為前面的 int idx, 導致 compiler 認成 for
裡面的 local variable 是 for loop 裡面自己的)
int max = 0;
int idxCnt = 10;
int arr[10];
for (int idx = 0; max = 5566; idx < idxCnt; idx++) {
arr[idx] = idx;
}
cout << max << endl;
actual output: 0
wanted output: 5566 (dont know how to modify the above code)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.137.133.35 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/ask/M.1725382557.A.79E.html
1F:推 cuteSquirrel: 另外,建議max改名字為maxValue 避免撞名 09/04 02:50
2F:→ cuteSquirrel: 盡量不要取和內建function同樣的名字,避免覆蓋。 09/04 02:50
3F:推 cuteSquirrel: 如果只是要assign5566 在外面改就可以了。 09/04 02:54
4F:→ cuteSquirrel: 回圈跑十次assign 5566並沒有額外獲得好處。 09/04 02:54
5F:推 andy90498: 在for loop裡面弄一個新的變數 把max的值存在新的變數 09/04 03:32
6F:→ andy90498: 出了loop之後再使用新的變數去印出 09/04 03:33
7F:→ kobe8112: 我比較好奇你是看哪本書這樣教寫for的? 09/04 08:53
8F:→ fun5566: 新的C才可以這樣寫,舊的C不可以這樣寫(的樣子). 09/04 15:47
9F:→ fun5566: me friend 15:47 這樣僅提示 1半,誰看得懂? (逃~) 09/04 15:57
10F:→ kobe8112: 不是,我知道他是想在init-clause初始化多個變數, 09/04 16:32
11F:→ kobe8112: 但這程式碼這樣編的過嗎? 我隨便找了幾個編譯器都不行啊 09/04 16:33
12F:→ cuteSquirrel: ,可以 ;不行。實務上不建議這樣混合不相關的初始化 09/04 17:34