C++ while 循环没有大括号?

时间:2021-01-11 16:01:08

标签: c++

我正在研究一些代码,我注意到一些我以前从未见过的东西。

有一个while循环,但没有大括号。 我应该解释一下代码的作用,但这部分和 while 令我困惑。

如果有人能解释为什么while循环没有大括号,我将不胜感激。

#include <cstring>
#include <cerrno>
#include <algorithm>
#include <functional>
#include <iostream>
#include <memory>

#include <sys/random.h>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

size_t n_children = 120;          //size_t is an unsigned integer 0 .. 4,294,967,295

typedef int64_t Konto;          // -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807, typedef abkürzung fü int64_t an Konto zugewiesen

Konto konto = 0;                // 64 bits long long

int main() {
  while (fork() && --n_children);   

  unsigned int transaktionen = 100;     // 
  while (transaktionen--) {             // 100 times
    int8_t value;                       //  8 bit signed char (-128 .. 127)
    if (getrandom(&value, sizeof(value), 0) == sizeof(value))
      konto += value;
  }

  cout << "My Konto value: " << konto << endl;
  return 0;
}

3 个答案:

答案 0 :(得分:3)

while 循环的语法是 while (<condidtion>) <statement>

语句可以是单条语句,也可以是花括号中的复合语句。 这里的语句只是 ;,空语句。

所以这相当于

while (fork() && --n_children){}

其中语句是复合语句,没有任何其他嵌套语句。 如果所有工作都在控制条件下完成,这也是首选的形式。

答案 1 :(得分:2)

与流行的看法相反,ifwhilefor 可以用分号终止,当它有一个空的正文并且没有正文已经可以表达足够的内容时。 例如,这是一个无限循环:

while(1);

这相当于

while(1) {}

在您的示例中:

while (fork() && --n_children);

这会不断调用 fork() 函数并递减 n_children,直到这两个表达式中的至少一个的计算结果为 0false。这当然相当于:

while (fork() && --n_children) {}

如果 n_children 变为 0 或 fork() 返回假值,则循环停止。换句话说,这两个表达式的计算结果都必须为 true/1,循环才能继续,因此 &&

使用空 for 循环计算 C 字符串长度的简短示例:

int main()
{
    char str[] = "A String";
    for(len = 0; str[len] != '\0'; len++);  
    printf("Length: %d", len); 
}

答案 2 :(得分:1)

C/C++ 中的 while 循环定义为:-

while condition
   statement or block

块是一对大括号内的一系列语句。语句只是一行以分号结尾的代码。语句可以为 null 或为空,因此 ';'是一个有效的陈述。 因此,在这种情况下,while 循环中的条件会在 while 循环的内容为空时重复测试,因此它“旋转”不断地重新测试条件(在这种情况下,分叉)。这不是理想的模式,有时称为“忙等待”循环,它会消耗大量 CPU 时间。 在这个例子中,更清晰的写法是:-

for (int count = 0 ; count < n_children ; ++count)
{
  fork ();
}

较旧的编译器可能会生成更高效的代码,但如今差异非常小。