简体   繁体   English

什么条件适用于?

[英]Which condition is true in While?

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? 有没有一种方法能够捕获这个而不用在if块内部重复它们? I am using C language. 我正在使用C语言。

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

You could use comma expressions, ie something like (expr1,expr2) , which are always evaluated left to right with a sequence point at each , ; 你可以使用逗号表达式,即像(expr1,expr2)它们总是从左向右计算在每个序列点, ; So you may rely on that expr1 is evaluated before expr2 , whereas the latter serves as the comma expression's result then. 所以,你可以依赖于expr1之前评估expr2 ,而后者作为逗号表达式的结果,那么,。

With that, the following should work, and x will bee in the range of 0..3 , depending on which condition got true: 这样,以下应该可以工作, x将在0..3的范围内,具体取决于哪个条件成立:

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 || 注意if-else链,因为|| operator short-circuits (ie the second operand isn't even evaluated if the first is already true ), if eg ll0 is true the other values aren't going to be correctly assigned. 运算符短路(即,如果第一个操作数已经为true ,则甚至不评估第二个操作数),如果例如ll0为真,则不会正确分配其他值。

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. 因此,请确保您确实要事先存储它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM