Share via

bitand : keyword vs function in C++

Anup Kale 21 Reputation points
2022-03-26T16:01:59.783+00:00

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, why is 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?)
Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2022-03-26T17:52:10.097+00:00

In my opinion, bitand is equivalent to &, and *bitand(d, e) is *&(d, e). Since ',' is an operator too, returning e, the result is *&e, which is 37, because '&' is also the "address-of" operator.

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. WayneAKing 4,936 Reputation points
    2022-03-26T19:50:24.42+00:00

    As Viorel pointed out, bitand is a synonym for & and may be
    replaced via a simple macro substitution.

    bitand
    https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/bitand?view=msvc-170

    Bitwise AND operator: &
    https://learn.microsoft.com/en-us/cpp/cpp/bitwise-and-operator-amp?view=msvc-170

    When you write bitand(d, e) you are NOT writing a function call.

    You are writing a parenthesized expression (d, e). The comma in
    this expression is used as the comma operator, not as a separator.

    Comma Operator: ,
    https://learn.microsoft.com/en-us/cpp/cpp/comma-operator?view=msvc-170

    The rules for this operator mean that the value of this expression
    is the value of the second item which is e.

    So bitand(e) is evaluated, which is identical to &(e) which yields
    the address of e. When you prefix the asterisk you dereference this
    address which yields the value in e.

    bitand(d, e)

    is

    &(d, e)

    is

    &(e)

    is

    address of e

    and

    *&(e)

    equals 37, the value in e.

    • Wayne

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.