我正在研究一些代码,我注意到了一些我以前从未见过的东西。
有一个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;
}发布于 2021-01-12 00:06:55
while循环的语法是while (<condidtion>) <statement>
该语句可以是单个语句,也可以是大括号中的复合语句。这里的语句就是;,也就是空语句。
所以这相当于
while (fork() && --n_children){}其中语句是复合语句,没有任何其他嵌套语句。如果所有的工作都是在控制条件下完成的,这也是优选的形式。
发布于 2021-01-12 00:19:47
与流行的看法相反,当if、while和for有一个空的正文时,可以用分号终止,并且可以在没有正文的情况下表达足够的内容。例如,这是一个无限循环:
while(1);这相当于
while(1) {}在您的示例中:
while (fork() && --n_children);这会一直调用fork()函数并递减n_children,直到这两个表达式中至少有一个表达式的计算结果为0或false。当然,这相当于:
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);
}发布于 2021-01-12 00:10:05
C/C++中的while循环定义为:
while condition
statement or block块是一对大括号中的一系列语句。语句只是一行以分号结尾的代码。语句可以为null或空,因此';‘是有效的语句。因此,在这种情况下,while循环中的条件被重复测试,而while循环的内容为空,因此它在持续重新测试该条件时“旋转”(在本例中为fork‘’ing)。这不是一个理想的模式,有时被称为“繁忙等待”循环,它将消耗大量的CPU时间。在这个例子中,一种更清晰的方式是:-
for (int count = 0 ; count < n_children ; ++count)
{
fork ();
}较老的编译器可能会产生更有效的代码,但现在这种差异将非常微不足道。
https://stackoverflow.com/questions/65670318
复制相似问题