Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rationale for == having higher precedence than bitwise AND, XOR, and OR? [closed]

In C++, what is the rationale for == and != having higher precedence than bitwise AND, XOR, and OR?

It would seem to me more natural to have operator== and operator!= come after operator&, operator^, and operator|. I'd like to understand the motivation so that I can better remember the ordering.

For example, I would think the following kind of usage would be common:

if (bitFields & value == 0) { // Incorrect test.
  // Do Something.
}

Since the == result is either 1 or 0, why would you ever want to use it for bitwise operations? Instead, the above must be written as:

if ((bitFields & value) == 0) { // Correct test.
  // Do Something.
}

to get the intended meaning where the bitwise AND is done before the comparison to zero.

like image 858
WilliamKF Avatar asked Jun 07 '12 13:06

WilliamKF


1 Answers

  1. It is historical from C
  2. Consider using functions in your if statement

e.g.

if (func1() == 2 & func2() == 3)

With the precedence of == being higher that & ensures that both functions are called.

like image 173
Ed Heal Avatar answered Nov 15 '22 21:11

Ed Heal