如何获得if表达式的哪一部分为真?

时间:2013-08-29 11:00:56

标签: c++ objective-c c if-statement

假设我有以下代码:

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.
}

6 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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
{

}

答案 2 :(得分: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
}

答案 3 :(得分:0)

如果没有switch,您只能使用orif语句:

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 ...区块的四个条件中的哪一个。

答案 4 :(得分:0)

如果您需要了解程序原因,即根据具体情况运行不同的代码,您可以执行以下操作

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

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

答案 5 :(得分: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);