8

自从我上次编程以来已经有一段时间了,我似乎忘记了使用空的“for循环”来创建无限循环是否可以接受?

for(;;)

目前我在一个程序中使用这种方法,让它反复要求用户输入两个数值,一个为程序中的每个双精度变量。然后程序调用一个函数并计算这两对数字的总和。

要终止程序,我有“if”语句来检查用户输入值是否为零,如果值为零,则程序使用“返回 0;”终止。争论。

程序在将值分配给变量后立即检查每个用户输入值是否为零。


所以真正的问题是:这是让我的程序按照我描述的方式做的正确方法吗?还是有更多/更好/可接受的编程方式?

其次,像我在这个程序中那样使用“返回 0”参数有什么问题吗?

如果您认为我将要写的内容或意思难以理解,请回复,我会花更多时间来写所有内容。

4

9 回答 9

5

What you're doing is perfectly fine, and an idiomatic way of writing and exiting an infinite loop.

于 2011-05-03T10:00:18.727 回答
5

我总是使用while(true)无限循环

于 2011-05-03T10:09:57.430 回答
2

This is valid, you can go ahead with your code.

于 2011-05-03T09:59:10.713 回答
2

我在几个地方看到过这个:

#define forever for(;;)

forever {

}

不确定我会推荐它。

于 2011-05-03T10:05:28.777 回答
2

for(;;)以及while(1)两者都可以接受。这些只是语言提供的条件循环,您可以根据您的要求使用它们来进行无限循环。

于 2011-05-03T10:02:51.677 回答
1

Yes, it's totally acceptable. Once you have an exit condition (break or return) in a loop you can make the loop "infinite" in the loop statement - you just move the exit condition from the loop statement into the loop body. If that makes the program more readable you of course can do that.

于 2011-05-03T09:59:41.660 回答
0

For an infinte loop for (;;) is fairly common practice. But if you do have a condition, such a non-zero user input, you could always have that check done in a while loop.

于 2011-05-03T10:01:24.653 回答
0

您还可以使用带条件的 while 循环重复请求用户输入。

while (condition) {
  ...
}

您可以使用 .

于 2011-05-03T10:01:43.540 回答
0

您所描述的内容可以正常工作,但值得一提的是,某些严格的编码标准(即MISRA)会不赞成return在函数结束之前使用 a 。

如果您的代码受此类标准的约束,那么您可以使用do-while带有合适退出条件的循环:

do {
   // get userinput
   if (userinput != '0')
   {
       // do stuff 
   }
} while (userinput != '0');
于 2011-05-03T11:18:28.123 回答