gpt4 book ai didi

c - 在循环中编写声明

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:42 24 4
gpt4 key购买 nike

我想到了以下问题:
这两种运行代码的方式有什么区别吗?
也许在内存管理方面?

int main(){
int counter = 1;
while(1){
int arr_one[3] = { 0, 1, 2 };
int arr_two[3] = { 3, 4, 5 };
int arr_three[3] = { 6, 7, 8 };
if(counter == 1){
for(int i = 0; i < 2; i++){ printf("%d\n", arr_one[i]); }
}
if(counter == 2){
for(int i = 0; i < 2; i++){ printf("%d\n", arr_two[i]); }
}
if(counter == 3){
for(int i = 0; i < 2; i++){ printf("%d\n", arr_three[i]); }
}
if(counter >= 4){ counter = 1; } else { counter++; }
}
return 0;
}

//

int main(){
int counter = 1;
while(1){
if(counter == 1){
for(int i = 0; i < 2; i++){
int arr_one[3] = { 0, 1, 2 };
printf("%d\n", arr_one[i]);
}
}
if(counter == 2){
for(int i = 0; i < 2; i++){
int arr_two[3] = { 3, 4, 5 };
printf("%d\n", arr_two[i]);
}
}
if(counter == 3){
for(int i = 0; i < 2; i++){
int arr_three[3] = { 6, 7, 8 };
printf("%d\n", arr_three[i]);
}
}
if(counter >= 4){ counter = 1; } else { counter++; }
}
return 0;
}

//这是我正在使用的代码的简化版本。
因为我在 Arduino 以及更大的阵列上运行代码,所以内存非常紧张。目前我有第一个示例中所示的代码,因为我还没有读过很多关于 C 的核心工作原理的文章。我希望你能帮助我!提前致谢!

最佳答案

严格来说,C 甚至没有堆栈,但是大多数实现都使用堆栈,而您的可能有。

也就是说,最好将变量限制在使用它们所需的最内层范围内。这样一来,它们占用堆栈空间的时间不会超过需要的时间,并且它们对不需要它们的作用域不可见。

所以你的第二种方法更可取。

关于c - 在循环中编写声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53212458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com