Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)
like image 624
ianupkale Avatar asked Jul 03 '26 08:07

ianupkale


1 Answers

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.

like image 65
Nathan Pierson Avatar answered Jul 04 '26 23:07

Nathan Pierson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!