c - 如何在 C 中编写 for 循环

标签 c loops for-loop

<分区>

为什么下面的代码循环了 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/

相关文章:

javascript - 我应该如何在javascript中循环遍历and "associative object"?

python - 将字典的键值对分配用作 for 循环中的迭代器

c - 在这种情况下如何修复 "Segmentation Fault"

c - 嵌入式编程中的输入和输出有什么区别?

jquery - 搜索变量的标签

电子邮件服务器设计 : Avoiding Loops

c - 为什么C语言中4个字节会出现一个char字符

c - C 和 OpenMP 中的嵌套循环优化

c# - 获取位图的某个正方形区域

java - 在循环内创建对象