Search code examples
c++visual-c++bitwise-operatorsbitwise-and

bitand : keyword vs function in C++


I've tried using the alternative bitwise operator 'bitand' in below simple code. Its appears that I can use bitand as a keyword as well as a function in Visual C++, both yielding different results, can anyone explain this discrepancy?

int d = 12, e = 37;
std::cout << (d & e) << std::endl; //4
std::cout << (d bitand e) << std::endl; //4
std::cout << *bitand(d, e) << std::endl; //37
int* bit_and = bitand(d, e);
std::cout << *bit_and << std::endl; //37 (should it be 4?)

Solution

  • Despite appearances, bitand(d, e) is not invoking a function named bitand and passing it the arguments d and e. bitand is just another way of spelling &.

    So your code is actually identical to &(d, e). & isn't a function, so what's the comma doing here? It is the lesser-known built-in comma operator. It evaluates and discards the first argument, then evaluates and returns the second argument. So (d, e) is the same as e, and your code boils down to &e.

    So despite the code saying bitand, there's no bitwise and happening here. It's acting as the unary address-of operator and returning a pointer that points to e. That's why you have to dereference it with unary *, and why the value after dereferencing is 37 not 4.


    As an aside, if you're using clang or gcc, if you enable -Wunused (which is included in -Wall), the compiler will issue a warning that you're discarding a value with no effect, like so:

    <source>:8:26: warning: left operand of comma operator has no effect [-Wunused-value]
        8 |     std::cout << *bitand(d, e) << std::endl; //37
          |               
    

    Which would have given you a heads-up that this wasn't acting like a function invocation but instead something else.