c - 而对于 : what is the best?

标签 c for-loop while-loop cycle

<分区>

如果我可以用 for 和 while 做一个循环,我应该选择哪个?

[为]

int num = 10;
int i;

for (i=0; i<num; i++)
{
    /* ... */
}

[同时]

int num = 10;
int i = num;

while ( i-- )
{
    /* ... */
}

最佳答案

forwhile 之间的选择只是为了清楚起见:

K&R 。第 1 章 For 语句:

The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.

关于c - 而对于 : what is the best?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21207024/

相关文章:

C编程: how to fopen a designated file and dynamically allocate its contents into a 2D array?

c - 消息队列不接受 0 作为参数

C++ for structure in vectors access index or use reference instead value

javascript - 在控制台日志中看不到对象侧左侧的数字

c - 辅助线程中的信号处理

c - 如何使用scanf检查用户是否输入了整数

java - java中for元素包含null

javascript - jQuery while object.hasClass

javascript - 为什么我的数组中的所有日期元素都是相同的日期?

Bash 使用 while read 语法附加到变量