Writing declarations in a loop

4115 views c
6

The following question came to my mind:
Is there any difference between these two ways of running code?
Perhaps in memory management?

int main(){
    while(1){
        int arr_one[3] = { 0, 1, 2 };
        int arr_two[3] = { 3, 4, 5 };
        int arr_three[3] = { 6, 7, 8 };
        int counter = 1;
        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(){
    while(1){
        int counter = 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;
}

// This is a simplified version of code, which I am using.
Because I'm running the code on an Arduino, as well as with larger arrays, memory is pretty tight. Currently I have the code as shown in the first example, because I haven't read a lot about how C works at its heart. I hope you could help me out! Thanks in advance!

answered question

1 Answer

5

Strictly speaking, C doesn't even have a stack, however most implementation use one, and yours likely does.

That being said, it's best to restrict variables to the innermost scope needed to use them. That way, they don't consume stack space longer than needed and they aren't visible to scopes that don't need them.

So your second approach is preferable.

posted this

Have an answer?

JD

Please login first before posting an answer.