C 中的循环 - for() 或 while() - 哪个最好? [英] Loops in C - for() or while() - which is BEST?
问题描述
for() 或 while() - 哪个最好?
for() or while() - which is BEST?
for (i=1; i<a; i++)
/* do something */
或
i=1;
while (i<a) {
/* do something */
i++;
}
推荐答案
第一种是惯用的方式;这是大多数 C 编码人员希望看到的.不过,我要指出的是,大多数人也希望看到
The first is the idiomatic way; it is what most C coders will expect to see. However, I should note that most people will also expect to see
for(i = 0; i < a; i++)
请注意,循环从零开始.这将执行a
次.如果您要编写一个 while
循环,它与上面的 for
循环等效,我强烈建议您将其编写为 for
环形.同样,这是 C 编码人员希望看到的.此外,作为 for
循环更容易阅读,因为所有内容(初始化、循环条件、每次迭代后要执行的表达式)都在一行中.对于 while
循环,它们分散开来阻碍可读性.
Note that the loop starts at zero. This will do something a
times. If you're going to write a while
loop that is equivalent to a for
loop as above I strongly encourage you to write it as a for
loop. Again, it is what C coders expect to see. Further, as a for
loop it is easier to read as everything (initialization, loop condition, expression to be executed after each iteration) are all on one line. For the while
loop they are spread out hindering readability.
但是请注意,在某些情况下,看似等效的 for
和 while
循环实际上并非如此.例如:
Note, however, there are circumstances in which seemingly equivalent for
and while
loops are actually not. For example:
for(i = 0; i < 10; i++) {
if(i == 5) continue;
printf("%d
", i);
}
和
i = 0;
while(i < 10) {
if(i == 5) continue;
printf("%d
", i);
i++;
}
乍一看似乎是等价的,但实际上并非如此.for
循环将在控制台上打印 0--9
跳过 5
而 while
循环将打印 0--4
然后进入无限循环.
appear at first glance to be equivalent but they are not. The for
loop will print 0--9
skipping 5
on the console whereas the while
loop will print 0--4
on the console and then enter an infinite loop.
现在,处理您询问的简单情况.那些你没有问过的更复杂的案例呢?嗯,这真的取决于,但一个很好的经验法则是:如果你要重复某件事固定的预定次数,for
循环通常是最好的.否则,使用 while
循环.这不是一个硬性规定,但它是一个很好的经验法则.例如,你可以写
Now, that handles the simple case that you asked about. What about the more complex cases that you didn't ask about? Well, it really depends but a good rule of thumb is this: if you are going to repeat something a fixed pre-determined number of times, a for
loop is generally best. Otherwise, use a while
loop. This is not a hard-and-fast rule but it is a good rule-of-thumb. For example, you could write
unsigned int v;
unsigned int c;
for(c = 0; v; v >>= 1) c += v & 1;
但我认为大多数 C 程序员会这样写
but I think most C programmers would write this as
unsigned int v;
unsigned int c;
c = 0;
while(v) { c += v & 1; v >>= 1; }
或者,再举一个例子,如果你要读到文件末尾,那么你应该使用 while
循环.于是
Or, as another example, if you're going to read until the end of a file then you should use a while
loop. Thus
FILE *fp;
fp = fopen(path, "r");
while(fgets(buf, max, fp) != NULL) { /* something */ }
代替
FILE *fp;
for(fp = fopen(path, "r"); fgets(buf, max, fp) != NULL; ) { /* something */ }
现在,进入宗教领域,这就是为什么我更喜欢 while(1)
作为对 for(;;)
进行无限循环的正确方法.
Now, reaching into religious territory, this is why I prefer while(1)
as the right way to do an infinite loop over for(;;)
.
希望有所帮助.
这篇关于C 中的循环 - for() 或 while() - 哪个最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!