循环编写声明

时间:2018-11-08 16:50:44

标签: c

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

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的工作原理了解甚少。 我希望你能帮助我! 预先感谢!

3 个答案:

答案 0 :(得分:4)

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

话虽如此,最好将变量限制为使用它们所需的最深范围。这样,它们不会消耗比所需时间更长的堆栈空间,并且不需要它们的作用域也看不到它们。

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

答案 1 :(得分:1)

C标准包含此类信息。该标准设置了许多确定程序输出的规则。该标准不在乎如何获得该输出,使用了多少内存,花费了多长时间等等...

因此,通常无法回答您的问题。相反,它取决于所使用的平台和所使用的编译器。

现代的编译器非常擅长优化代码,因此几乎不可能预测编写C代码的特定方式是否会改善所得程序。

最好的建议是以易于理解的方式编写代码,并让编译器进行优化。如果发现性能很差,请分析代码以找出瓶颈。

答案 2 :(得分:0)

在arduino上,最好获得一些非常优化的代码。它不是Atari 2600,可以,但是仍然。

这里有一些代码可以为您节省很多空间(请注意,该代码将解决您的帖子中所说的内容。它可能对您不起作用)。

int main() {
    int counter = 0;
    int arr[3] = {0, 1, 2};
    if (counter < 3) {
        for (int i = 0; i < 2; i++)
            printf("%d\n", arr[i] + 3 * counter);//better replace 3 with arr lenth.
        counter++;
    } else
        counter = 1;
}