C语言 For vs. while 在 C 编程中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2950931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:32:41  来源:igfitidea点击:

For vs. while in C programming?

cloopsfor-loopwhile-loop

提问by user355546

There are three loops in C: for, while, and do-while. What's the difference between them?

有三个环在C: ,forwhiledo-while。它们之间有什么区别?

For example, it seems nearly all whilestatements can be replaced by forstatements, right? Then, what's the advantage using while?

例如,似乎几乎所有while语句都可以用for语句替换,对吗?那么,使用 的优势是什么while

回答by Robert Greiner

A while loopwill always evaluate the condition first.

一个while循环总是首先评估条件。

while (condition) {
  //gets executed after condition is checked
}

A do/while loopwill always execute the code in the do{}block first and then evaluate the condition.

做/ while循环会一直执行在代码do{}块,然后再评估条件。

do {
  //gets executed at least once
} while (condition); 

A for loopallows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.

一个for循环允许你启动一个计数器变量,检查条件和方式来增加您的柜台都在一行。

for (int x = 0; x < 100; x++) {
   //executed until x >= 100
}

At the end of the day, they are all still loops, but they offer some flexibility as to how they are executed.

归根结底,它们仍然是循环,但它们在如何执行方面提供了一些灵活性。

Here is a great explanation of the reasoningbehind the use of each different type of loop that may help clear things up. Thanks clyfe

这是对使用每种不同类型循环背后的推理的一个很好的解释,可能有助于澄清问题。由于clyfe

The main difference between the for's and the while's is a matter of pragmatics: we usually use forwhen there is a known number of iterations, and use whileconstructs when the number of iterations in not known in advance. The whilevs do ... whileissue is also of pragmatics, the second executes the instructions once at start, and afterwards it behaves just like the simple while.

for's 和while's之间的主要区别在于语用问题:我们通常for在迭代次数已知while时使用,而在迭代次数事先未知时使用构造。该whileVSdo ... while问题也是语用学,第二执行一次在启动的指令,之后它的行为就像简单的一段时间。



For loops are especially nice because they are concise. In order for this for loop

For 循环特别好,因为它们很简洁。为了这个for循环

for (int x = 0; x < 100; x++) {
   //executed until x >= 100
}

to be written as a while loop, you'd have to do the following.

要编写为 while 循环,您必须执行以下操作。

int count = 0;
while (count < 100) {
  //do stuff
  count++;
}

In this case, there's just more stuff to keep up with and the count++;could get lost in the logic. This could end up being troublesome depending on where countgets incremented, and whether or not it should get incremented before or after the loop's logic. With a forloop, your counter variable is always incremented before the next iteration of the loop, which adds some uniformity to your code.

在这种情况下,只有更多的东西要跟上,并且count++;可能会迷失在逻辑中。这最终可能会很麻烦,这取决于在哪里count增加,以及它是否应该在循环逻辑之前或之后增加。对于for循环,您的计数器变量始终在循环的下一次迭代之前递增,这为您的代码增加了一些一致性。



For the sake of completeness, it's probably meaningful to talk about breakand continuestatements here which come in handy when doing loop processing.

为了完整起见,在这里讨论breakcontinue语句可能很有意义,这些语句在进行循环处理时会派上用场。

breakwill instantly terminate the current loop and no more iterations will be executed.

break将立即终止当前循环,不再执行迭代。

//will only run "do stuff" twice
for (int x = 0; x < 100; x++) {
  if (x == 2) {
    break;
  }
  //do stuff
}

continuewill terminate the current iterationand move on to the next one.

continue将终止当前迭代并进入下一个迭代

//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++) {
  if (x == 2) {
    continue;
  }
  //do stuff
}

Note that in a for loop, 'continue' evaluates the 'part3' expression of 'for (part1; part2; part3)'; in contrast, in a while loop, it just jumps to re-evaluate the loop condition.

请注意,在 for 循环中,'continue' 计算 'for (part1; part2; part3)' 的 'part3' 表达式;相反,在 while 循环中,它只是跳转以重新评估循环条件。

回答by psanzani

If there is a strong concern about speed and performance, the best approach is to verify the code produced by the compiler at the assembly level.

如果非常关注速度和性能,最好的方法是在汇编级别验证编译器生成的代码。

For instance, the following code shows that the "do-while" is a bit faster. This because the "jmp" instruction is not used by the "do-while" loop.

例如,以下代码显示“do-while”要快一些。这是因为“do-while”循环不使用“jmp”指令。

BTW, in this specific example, the worst case is given by the "for" loop. :))

顺便说一句,在这个特定的例子中,最坏的情况是由“for”循环给出的。:))

int main(int argc, char* argv[])
{
    int i;
    char x[100];

    // "FOR" LOOP:
    for (i=0; i<100; i++ )
    {
        x[i] = 0;
    }

    // "WHILE" LOOP:
    i = 0;
    while (i<100 )
    {
        x[i++] = 0;
    }

    // "DO-WHILE" LOOP:
    i = 0;
    do
    {
        x[i++] = 0;
    }
    while (i<100);

    return 0;
}

// "FOR" LOOP:

// “for”循环:

    010013C8  mov         dword ptr [ebp-0Ch],0
    010013CF  jmp         wmain+3Ah (10013DAh)

  for (i=0; i<100; i++ )
  {
      x[i] = 0;
    010013D1  mov         eax,dword ptr [ebp-0Ch]  <<< UPDATE i
    010013D4  add         eax,1
    010013D7  mov         dword ptr [ebp-0Ch],eax
    010013DA  cmp         dword ptr [ebp-0Ch],64h  <<< TEST
    010013DE  jge         wmain+4Ah (10013EAh)     <<< COND JUMP
    010013E0  mov         eax,dword ptr [ebp-0Ch]  <<< DO THE JOB..
    010013E3  mov         byte ptr [ebp+eax-78h],0
    010013E8  jmp         wmain+31h (10013D1h)     <<< UNCOND JUMP
  }

// "WHILE" LOOP:

// “WHILE”循环:

  i = 0;
  010013EA  mov         dword ptr [ebp-0Ch],0
  while (i<100 )
  {
      x[i++] = 0;
    010013F1  cmp         dword ptr [ebp-0Ch],64h   <<< TEST
    010013F5  jge         wmain+6Ah (100140Ah)      <<< COND JUMP
    010013F7  mov         eax,dword ptr [ebp-0Ch]   <<< DO THE JOB..
    010013FA  mov         byte ptr [ebp+eax-78h],0
    010013FF  mov         ecx,dword ptr [ebp-0Ch]   <<< UPDATE i
    01001402  add         ecx,1
    01001405  mov         dword ptr [ebp-0Ch],ecx
    01001408  jmp         wmain+51h (10013F1h)      <<< UNCOND JUMP
  }

// "DO-WHILE" LOOP:

// “DO-WHILE”循环:

i = 0;
.  0100140A  mov         dword ptr [ebp-0Ch],0
  do
  {
      x[i++] = 0;
    01001411  mov         eax,dword ptr [ebp-0Ch]   <<< DO THE JOB..
    01001414  mov         byte ptr [ebp+eax-78h],0
    01001419  mov         ecx,dword ptr [ebp-0Ch]   <<< UPDATE i
    0100141C  add         ecx,1
    0100141F  mov         dword ptr [ebp-0Ch],ecx
    01001422  cmp         dword ptr [ebp-0Ch],64h   <<< TEST
    01001426  jl          wmain+71h (1001411h)      <<< COND JUMP
  }
  while (i<100);

回答by hoang

For the sake of readability

为了可读性

回答by Michael Mrozek

They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that

它们都是可以互换的;您可以选择一种类型并永远使用它,但通常对于给定的任务来说,一种更方便。这就像在说“为什么有 switch,你可以只使用一堆 if 语句”——是的,但是如果检查变量的一组值是一种常见的模式,那么如果有语言特性,它会很方便也更容易阅读要做到这一点

回答by Justin Ethier

If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:

如果您希望在条件为真时执行循环,而不是执行特定次数的迭代,那么其他人更容易理解:

while (cond_true)

than something like this:

比这样的:

for (; cond_true ; )

回答by Armstrongest

Remember, a forloop is essentially a fancy whileloop. They're the same thing.

请记住,for循环本质上是一个花哨的while循环。它们是同一回事。

while <some condition is true> {
   // do some stuff
   // possibly do something to change the condition
}


for ( some var, <some condition is true>; increment var ) {

}

The advantage of a for loop is that it's harder to accidentally do an infinite loop. Or rather, it's more obvious when you do one because you generally put the loop var in the initial statement.

for 循环的优点是更难意外地执行无限循环。或者更确切地说,当你做一个时会更明显,因为你通常将循环变量放在初始语句中。

A whileloop is more clear when you're not doing a standard incrementing pattern. For example:

一个while循环更加清晰,当你没有做一个标准的递增模式。例如:

int x = 1;
while( x != 10 ) {
  if ( some condition )
     x = 10;
  else 
     x += 5;
}

回答by abespalov

You should use such a loop, that most fully conforms to your needs. For example:

您应该使用这样一个最完全符合您需求的循环。例如:

for(int i = 0; i < 10; i++)
{
    print(i);
}

//or

int i = 0;
while(i < 10)
{
    print(i);
    i++;
}

Obviously, in such situation, "for" looks better, than "while". And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.

显然,在这种情况下,“for”看起来比“while”更好。当某些操作必须在检查循环条件之前已经完成时,应该使用“do while”。

Sorry for my bad english).

对不起,我的英语不好)。

回答by Cam

One common misunderstanding withwhile/forloops I've seen is that their efficiency differs. Whileloops and forloops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.

我见过的对while/for循环的一个常见误解是它们的效率不同。While循环和for循环同样有效。我记得我高中的计算机老师告诉我,当你必须增加一个数字时,for 循环对迭代更有效。事实并非如此。

Forloops are simply syntactically sugaredwhileloops, and make iteration code faster to write.

For循环只是语法上加糖的while循环,使迭代代码的编写速度更快。

When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the whileand forsyntaxes are lost, and they become exactly the same.

当编译器获取您的代码并对其进行编译时,它会将其转换为计算机更易于理解并在较低级别(程序集)上执行的形式。在这个翻译过程中,whilefor语法之间的细微差别消失了,它们变得完全相同。

回答by David A. Gray

I noticed some time ago that a For loop typically generates several more machine instructions than a while loop. However, if you look closely at the examples, which mirror my observations, the difference is two or three machine instructions, hardly worth much consideration.

前段时间我注意到 For 循环通常比 while 循环生成更多的机器指令。但是,如果您仔细观察反映了我观察结果的示例,就会发现不同之处是两三个机器指令,几乎不值得考虑。

Note, too, that the initializer for a WHILE loop can be eliminated by baking it into the code, e. g.:

还要注意,WHILE 循环的初始化器可以通过将其烘焙到代码中来消除,例如:

static int intStartWith = 100;

The static modifier bakes the initial value into the code, saving (drum roll) oneMOV instruction. Of greater significance, marking a variable as static moves it outside the stack frame. Variable alignment permitting, it may also produce slightly smaller code, too, since the MOV instruction and its operands take more room than, for example an integer, Boolean, or character value (either ANSI or Unicode).

静态修改器将初始值烘焙到代码中,节省(鼓卷)一条MOV 指令。更重要的是,将变量标记为静态将其移出堆栈帧。在变量对齐允许的情况下,它也可能生成稍小的代码,因为 MOV 指令及其操作数比例如整数、布尔值或字符值(ANSI 或 Unicode)占用更多空间。

However, if variables are aligned on 8 byte boundaries, a common default setting, an int, bool, or TCHAR baked into code costs the same number of bytes as a MOV instruction.

但是,如果变量在 8 字节边界上对齐,则常见的默认设置、int、bool 或 TCHAR 烘焙到代码中的字节数与 MOV 指令的字节数相同。

回答by Pieter

A forsuggest a fixed iteration using an index or variants on this scheme.

Afor建议使用此方案的索引或变体进行固定迭代。

A whileand do... whileare constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.

A whileanddo... while是您在每次必须检查条件时使用的结构(除了一些类似索引的结构,见上文)。它们的不同之处在于第一次执行条件检查的时间。

You can use either construct, but they have their advantages and disadvantages depending on your use case.

您可以使用任何一种构造,但它们各有优缺点,具体取决于您的用例。