Search code examples
c++if-statementbitwise-operatorslogical-operators

Difference between " | " or " & " for calculations and inside IF statement


I'm trying using | inside a IF (or SWITCH) statement to compare if a variable is equal to a number or another. But I found (described as an example in code below) that using | operator to two numbers that I wanna compare is the same result as I put an || for two comparisons. But if I declare another variable that ORs these two numbers using |, the if statement won't execute:

(This is "almost" the full code)

using namespace std;
short n1 = 5, n2 = 3, n3, nResult;
n3 = 3; // used for two comparisons
nResult = n1 | n2; // used for the second comparison (IF statement)
    
bitset<16> n1_b(n1), n2_b(n2), n3_b(n3), nr_b(nResult); // I used bitset to check their binary value
    
if (n3 == nResult) 
    cout << "nResult YES";
else if (n3 == n1 | n2) 
    cout << "n1 | n2 YES";
    
/* cout << endl << n1_b << endl << n2_b << endl << n3_b << endl << endl << nr_b; */

The output is always n1 | n2 YES. Why using m3 == n1 | n2 inside IF statement gave the same result as using n3 == n1 || n3 == n2, and why if I ORed before will not execute?


Solution

  • The expression in this if statement

    else if (n3 == n1 | n2) 
    

    is equivalent to

    else if ( ( n3 == n1 ) | n2) 
    

    The subexpression n3 == n1 ( 3 == 5 ) yields boolean value false that used in expressions is implicitly converted to 0.

    So

    0 | n2
    

    gives non-zero value equal to n2.

    Thus the result of the expression is boolean true..

    As for this if statement

    if (n3 == nResult) 
    

    then nResult calculated like nResult = n1 | n2; is equal to 7 that is not equal to n3.