这是一个循环吗?

Is this a loop?

这是一个循环,不是循环,还是既是循环又不是循环?如果你要计算程序中的循环次数,你会计算这个吗?

do {
   ...
}while(0);

我很好奇,因为我正在与一个项目合作的人要求他计算程序中的循环次数。

在 C 标准中,C11,章节 §6.8.5,迭代语句,列出

iteration-statement:

       while ( expression ) statement
       do statement while ( expression ) ;
       for ( expression opt ; expression opt ; expression opt ) statement
       for ( declaration expression opt ; expression opt ) statement

上面提到了do statement while ( expression ) ;,所以是的,是个循环(迭代)语句不考虑的个数它在特定 implementation/usage.

中进行的迭代次数

FWIW,循环一次。

要添加更多说明,quoting from Wikipedia,(强调我的

A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code "inside" the loop (the body of the loop, shown below as xxx) is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.

从某种意义上说,这是一个循环,但实际上不是。它在技术上是一个循环,因为您使用的是循环语法,但您实际上所做的只是 运行 您 "loop" 中的代码一次,然后中断。我不会真的把它算作一个循环,因为你没有向你的程序添加任何算法运行时,所以把它算作一个循环是没有意义的。注意:不要这样做,这是毫无意义的错误编码习惯。

编辑:在下面的评论中感谢 Jeremy,至少在一种情况下此构造在 C 中很有用:do { ... } while (0) — what is it good for?

do {
   ...
}while(k);

现在迭代次数取决于 k 的值,现在你不能说只有当 k!=0kTrue 时才循环.

所以它基本上是一个循环。