0

Traditional programming with while-loop is done with a single parameter ex:

  • while(1) (or) while(a==b) (or) while(a&&b) (or) while(!a) etc
  • The code below takes two parameters in the while loop

    ssize_t r_read(int fd, void *buf, size_t size) 
    {
        ssize_t retval;
        while (retval = read(fd, buf, size), retval == -1 && errno == EINTR);
        return retval;
    }
    
    1. Is there any limit to the parameters inside the while loop?
    2. Is there any possible explanation for this or does this methodology have a name?
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Muzab
  • 133
  • 1
  • 10
  • 1
    See: [What does the comma operator `,` do in C?](http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c) – John Kugelman Aug 04 '15 at 14:44
  • 2
    I've always described them as 'compound boolean expressions'. One boolean is the result but, AFAIK, the complexity has no firm limit. The downside of lengthy expressions is that it gets easier to screw them up and more difficult to debug them. A liberal sprinkling of temp vars, and the resulting simpler expression in the while(), would have prevented a lot of SO posts. – Martin James Aug 04 '15 at 14:48

1 Answers1

3

while does not take parameters, but an expression. In your example, while is not taking 2 parameters, but an expression containing 2 subexpressions separated by the , operator. This operator executes both expressions but returns the value produced by the last expression.

In your sample, it is used as a trick to turn a loop into a one-liner, by doing the read() operation inside the while expression.

It's equivalent to this:

do {
    retval = read(fd, buf, size);
} while (retval == -1 && errno == EINTR);
Vii
  • 31
  • 5