Home > Mobile >  bitand : keyword vs function in C
bitand : keyword vs function in C

Time:03-27

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?)

CodePudding user response:

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.

CodePudding user response:

bitand is the keyword in C , equivalent of operator & with the identical behaviour, taking a single or double arguments depending on usage context.

*bitand(d, e)

is identical to

*&(d, e)

The result of the comma operator in the parentheses is a reference to the last variable

*&e

Getting the addresses of the variable and dereferencing obviously returns the variable value.

  • Related