作者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/cn.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