<分区>
为什么下面的代码循环了 5000 次而不是我期望的 5 次?
int height = 5;
for (int height; height > 0; height -= 1){
printf('Something') }
}
<分区>
为什么下面的代码循环了 5000 次而不是我期望的 5 次?
int height = 5;
for (int height; height > 0; height -= 1){
printf('Something') }
}
最佳答案
but when I run it, it does not iterate through the loop 5 times but rather something like 5000.
那是因为在 for
循环中声明了 height
shadows外面宣布的那个。所以你是
有效地使用未初始化的 height
,即 potentially undefined behaviour .
您可以省略声明以使用先前声明的值:
int height = 5;
for (; height > 0; height -= 1) {
printf("Something");
}
如果你不想改变高度
,你可以使用一个临时的:
int height = 5;
for (int x = height; x > 0; x -= 1) {
printf("Something");
}
这将使 height
保持不变。
另请注意,单引号中的值是多字节字符,而不是字符串。所以你不能将 'Something'
传递给 printf
。
关于c - 如何在 C 中编写 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47349181/