做循环完成后释放内存
do for loops deallocate memory after they finish
假设您编写了一个 for 循环:
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
for 循环是否创建了 10 个不同的 j
变量,它是否在完成循环后释放 i
和 j
?
我见过很多人这样做:
int i, j, k
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
//..All The Loops..//
在所有循环之前声明 i
j
k
变量有什么好处,还是只是个人喜好?
所有相关变量都在 automatic storage. They are destroyed when they go out of scope 中创建。这两个例子只是在不同的范围内声明变量。
在第一个示例中,i
的作用域为外循环,这意味着 i
仅在循环为 运行 时存在。循环开始时创建,循环结束时销毁:
for (int i = 0; i < 10; i++) { <- created here
<statements>
} <- destroyed here
与内循环中的j
相同:
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
在第二个例子中,变量的作用域是循环所在的外部块。因此变量在外部循环开始之前已经存在,并且在循环结束后它们继续存在。
{
...
int i, j, k; <- created here
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
...
...
} <- destroyed here
for (int i = 0; i < 10; i++)
只允许在C99或C11模式下使用,这是一种更现代的风格。
在使用非常旧的编译器时,您应该在使用前声明 i
。
假设您编写了一个 for 循环:
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
for 循环是否创建了 10 个不同的 j
变量,它是否在完成循环后释放 i
和 j
?
我见过很多人这样做:
int i, j, k
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
//..All The Loops..//
在所有循环之前声明 i
j
k
变量有什么好处,还是只是个人喜好?
所有相关变量都在 automatic storage. They are destroyed when they go out of scope 中创建。这两个例子只是在不同的范围内声明变量。
在第一个示例中,i
的作用域为外循环,这意味着 i
仅在循环为 运行 时存在。循环开始时创建,循环结束时销毁:
for (int i = 0; i < 10; i++) { <- created here
<statements>
} <- destroyed here
与内循环中的j
相同:
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
在第二个例子中,变量的作用域是循环所在的外部块。因此变量在外部循环开始之前已经存在,并且在循环结束后它们继续存在。
{
...
int i, j, k; <- created here
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
...
...
} <- destroyed here
for (int i = 0; i < 10; i++)
只允许在C99或C11模式下使用,这是一种更现代的风格。
在使用非常旧的编译器时,您应该在使用前声明 i
。