TryOmar's blog

By TryOmar, history, 14 months ago, In English

In my quest to count the bits in an integer's binary representation using recursion, I encountered a unexpected outcome due to operator precedence:

Working Code:

int f(int n) {
    return (n ? (n & 1) + f(n >> 1) : 0);
}

Not Working Code:

int f(int n) {
    return (n ? n & 1 + f(n >> 1) : 0);
}

The big difference? Operator rules. In the first code, it works because we use parentheses to make sure the "AND" operation happens first.

In the second code, missing parentheses cause the compiler to interpret it as n & (1 + f(n >> 1)), resulting in an incorrect bit count.

To avoid confusion and errors, always use parentheses to clarify your intended order of operations in programming.

Additionally, it's important to note that in C++ and many other programming languages, the plus (+) and minus (-) operators have higher precedence than the bitwise AND (&) and OR (|) operators. To understand the complete operator precedence hierarchy, you can refer to resources such as cppreference.com's operator precedence page.

  • Vote: I like it
  • -22
  • Vote: I do not like it

»
14 months ago, # |
  Vote: I like it +10 Vote: I do not like it

compiler literally warns you about this lmao

  • »
    »
    14 months ago, # ^ |
      Vote: I like it +24 Vote: I do not like it

    Yes. Especially, Clion.

  • »
    »
    14 months ago, # ^ |
    Rev. 2   Vote: I like it +10 Vote: I do not like it

    Yeah maybe, but at least I learned something today :D

    After gaining a better understanding of the precedence, I won't feel the need to include unnecessary parentheses in my code anymore. This will not only make the code clearer but also more concise.

    Eg. (Remove Last Bit)

    int RemoveLastBit(int n){
      return n & n - 1;
    }