Which condition is true in While?

Viewed 346

Sorry if this is too simple. I want to know which of the conditionals is happening exactly. Is there a way more able to capture this without repeating them inside the block with if structures? I am using C language.

while ( l < 0 || l > 2 || c < 0 || c > 2 )
3 Answers

You could use comma expressions, i.e. something like (expr1,expr2), which are always evaluated left to right with a sequence point at each ,; So you may rely on that expr1 is evaluated before expr2, whereas the latter serves as the comma expression's result then.

With that, the following should work, and x will bee in the range of 0..3, depending on which condition got true:

int x;
while ( (x=0,l < 0) || (++x,l > 2) || (++x,c < 0) || (++x,c > 2) )

You can assign them "on the fly" to previously declared variables:

bool ll0, lg2, cl0, cg2;
while((ll0 = l<0) || (lg2 = l>2) || (cl0 = c<0) || (cg2 = c>2)) {
    if(ll0) {
        // l is less than 0
    } else if(lg2) {
        // l is greater than 2
    } else if(cl0) {
        // c is less than 0
    } else if(cg2) {
        // c is greater than 2
    }
    // ...
}

Notice the if-else chain, as, since the || operator short-circuits (i.e. the second operand isn't even evaluated if the first is already true), if e.g. ll0 is true the other values aren't going to be correctly assigned.

That being said, to be honest I wouldn't bother - just repeat the conditional, if these are just integer variables these comparisons aren't going to cost you anything (actually, the compiler may even keep around the comparison value in some cases and recycle it).

You could use a loop without conditions, compute conditions in loop, and break if any of the conditions is true.

while (1)   // or for(;;)
{
  bool one = l < 0;
  bool two = l > 2;
  bool three = c < 0;
  bool four = c > 2;
  if (one || two || three || four) break;
  // bool variables are available there
}

If you want to get access to all conditions, you cannot use short-circuiting evaluation for them. So make sure you really want to store them beforehand.

Related