Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

C++ while loop without curly brackets?

i am studying some code and i notice something i never saw before.

There is a while loop but without the curly brackets. I should explain what the code does, but this part with the while is confusing me.

I would appreciate it, if someone can explain me why the while loop dont have curly brackets.

#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The syntax of a while loop is while (<condidtion>) <statement>

The statement can be a single statement or a compound statement in curly braces. Here the statement is just ;, the empty statement.

so this is equivalent to

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

Where the statement is a compound statement, without any other nested statements. Which is also the form to prefer if all work is done in the controlling condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...