7

I have a function func which returns true or false. Until func returns false, I want to keep calling it. What is the least awkward way to do this?

do {
  // do nothing
} while (func());

or..

while (func());

or..

while (func())
  if (!func())
    break;

All of them look really awkward and unintuitive to me. Is there another solution to this altogether?

4

4 回答 4

10

I think option B is most commonly used, but you should make it more obvious that you have an empty loop body:

while (func())
  ; // do nothing

or

while (func())  { /* do nothing */ }

As a side note, this looks like some kind of busy waiting. If this is the case, it can and should usually be avoided by using OS-provided synchronization primitives.

于 2012-04-10T22:13:35.100 回答
9

我以前写

while (func()) continue;

当我需要一个完整的忙等待循环时(这不是很常见)。关键字使得很难错过意图,并且它被编译掉了。:)

于 2012-04-10T22:23:23.793 回答
1

选项 B 的变体:

while (func())
{
    // no-op
}
于 2012-04-10T22:16:06.103 回答
0

好吧,第三个做了一些不同的事情——func每次迭代它会调用两次。

我猜你想要第二个,它不会让其他人感到困惑。

于 2012-04-10T22:14:39.453 回答