Home > Mobile >  do for loops deallocate memory after they finish
do for loops deallocate memory after they finish

Time:01-18

Let's say you wrote a for loop:

for (int i = 0; i < 10; i  )
   for (int j = 0; j < 10; j  )

Is that for loop creating 10 different j variables, and does it deallocate i and j after its done looping?

I have seen many people do this instead:

int i, j, k

for (i = 0; i < 10; i  )
   for (j = 0; j < 10; j  )
//..All The Loops..//

Is there any advantage of declaring the i j k variables before all of your loops, or is it just a personal preference?

CodePudding user response:

All of the variables in question are being created in automatic storage. They are destroyed when they go out of scope. The two examples are simply declaring the variables in different scopes.

In the first example, i is scoped to the outer loop, meaning i exists only while the loop is running. It is created when the loop begins, and it is destroyed when the loop ends:

for (int i = 0; i < 10; i  ) { <- created here
    <statements>
} <- destroyed here

Same with j in the inner loop:

for (int i = 0; i < 10; i  ) { <- i created here
    for (int j = 0; j < 10; j  ) { <- j created here
       <statements>
    } <- j destroyed here
} <- i destroyed here

In the second example, the variables are scoped to the outer block which the loops exist in. So the variables already exist before the outer loop begins, and they continue to exist after the loop ends.

{
    ...
    int i, j, k; <- created here

    for (i = 0; i < 10; i  )
        for (j = 0; j < 10; j  )
           ...

    ...
} <- destroyed here

CodePudding user response:

for (int i = 0; i < 10; i ) are only allowed in C99 or C11 mode, it's a more modern style.

You should declare i before use it when worked with very old compiler.

  •  Tags:  
  • Related