2013-08-29 45 views
1

假設我有這樣的代碼:如何獲得if表達式的哪一部分爲真?

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

除了打印'COUT <<「條件1 =」 << coundition1 <<「條件2 =」 <<條件2 ... '? –

+2

@captain:想要多解釋一下? –

+1

@captain是什麼讓你認爲他的'if'可以被改寫爲'switch'。如果他的'condition1'等實際上是變量,那麼它肯定不能,如果它們是任意表達式,它也不能。 –

回答

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 
} 
+0

是的,我需要這樣的東西.. –

+0

尾隨返回類型不是必須的btw – user1233963

+0

@ user1233963它贏得' t在C++ 14中,在C++ 11中是這樣。 – jrok

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 
} 
+1

一些if語句不能切換到開關,例如'if(str ==「something」)' – billz

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 ...區塊的四個條件中的哪一個。

0

如果您需要了解程序的原因,即運行取決於哪個條件爲真不同的代碼,你可以做這樣的事情

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

如果你只是想知道調試的原因,只是做了打印。

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 
{ 

} 
+0

+1電路評估是一個關鍵的觀察點。 – pablo1977

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); 
相關問題