1

假设我有如下代码:

if(condition1 || condition2 || condition 3 || condition4)
{
// this inner part will be executed if one of the conditions is true.
// Now I want to know by which condition this part is executed.
}
4

6 回答 6

5

我相信有更好的方法可以做到这一点,这里有一个:

int i = 0;
auto check = [&i](bool b)->bool
{
    if (!b) ++i;
    return b;
};

if (check(false) || // 0
    check(false) || // 1
    check(true)  || // 2
    check(false))   // 3
{
    std::cout << i; // prints 2
}
于 2013-08-29T11:14:48.847 回答
2

|| 是短路评估,所以你可以有这样的代码:

if(condition1 || condition2 || condition 3 || condition4)
{
    if (condition1 ) 
    {
            //it must be condition1 which make the overall result true
    }
    else if (condition2)
    {
            //it must be condition2 which make the overall result true
    }
    else if (condition3)
    {
            //it must be condition3 which make the overall result true
    }
    else
    {
            //it must be condition4 which make the overall result true
    }

    // this inner part will executed if one of the condition true. Now I want to know by which condition this part is executed.
}
else
{

}
于 2013-08-29T11:42:08.417 回答
0

如果条件相互独立,则需要单独检查,或者,如果它们属于一个变量,则可以使用 switch 语句

bool c1;
bool c2
if ( c1 || c2 )
{
    // these need to be checked separately
}


int i; // i should be checked for multiple conditions. Here switch is most appropriate
switch (i)
{
    case 0: // stuff
            break;
    case 1: // other stuff
            break;
    default: // default stuff if none of the conditions above is true
}
于 2013-08-29T11:07:11.470 回答
0

没有 aswitch你只能使用orandif语句:

if(condition1 || condition2 || condition 3 || condition4) {
  // this inner part will executed if one of the condition true. 
  //Now I want to know by which condition this part is executed.
  if ( condition1 || condition2 ) { 
    if ( condition1 ) 
       printf("Loop caused by 1");
    else 
       printf("Loop caused by 2");
  else 
    if ( condition3) 
       printf("Loop caused by 3");
    else
       printf("Loop caused by 4");
}

我不确定这是你见过的最有效的方法,但它会确定四种情况中的哪一种导致进入if ...区块。

于 2013-08-29T11:11:45.183 回答
0

如果您出于编程原因需要知道,即根据哪个条件为真运行不同的代码,您可以执行以下操作

if (condition1)
{
    ...
}
else if (condition2)
{
    ...
}
else if (condition3)
{
    ...
}
else if (condition4)
{
    ...
}
else
{
    ...
}

如果您只是出于调试原因想知道,只需打印输出即可。

于 2013-08-29T11:14:47.823 回答
0

逗号运算符呢?通过使用该逻辑运算符遵循短路评估方法,以下工作正常:

 int w = 0; /* w <= 0 will mean "no one is true" */
 if ( (w++, cond1) || (w++, cond2) || ... || (w++, condN) )
   printf("The first condition that was true has number: %d.\n", w);
于 2013-08-29T14:18:53.740 回答