Search code examples
c++bitwise-operatorsevaluation

Why do bitwise operators require parentheses?


Consider:

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;
    if(n&1 == 0)   // Without using brackets (n&1)
        cout << "Number is even";
    else
        cout << "Number is odd";
    return 0;
}

Output: odd // for n=6

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;
    if((n&1) == 0)
        cout << "Number is even";
    else
        cout << "Number is odd";
    return 0;
}

Output: even // for n=6

Do we have to use parentheses whenever we use bitwise operators?


Solution

  • According to operator precedence this expression:

    n&1==0
    

    is equivalent to:

    n&(1==0)
    

    which means result of operation 1==0 which is always false is used with binary AND with n. Boolean false is implicitly converted to int which is required by binary operation and value is 0. As binary AND with 0 is always 0 that code is convoluted way to say:

    if(0) 
        cout<<"Number is even";
    else
        cout<<"Number is odd";
    

    and 0 converted back to boolean as false so you always get "Number is odd" output. So yes, brackets are required in this case.

    my question is do we have to put bracket whenever we are using bitwise operators?

    No, you have to use them when other operations with higher precedence are involved. It does not have to be always, but if you prefer you can always put them.