0

In most programming languages (C#, JavaScript, Java) the order of operations precedence has that equality comparison come BEFORE bitwise comparisons.

This means that if you have a bit operation and an equality comparison on the same line (as in this javascript code):

if(2 & 15 === 2){
    //do something
}

You will get an unexpected result (it evaluates to 0 in JavaScript). C# throws an error if you try to do this and won't compile. Java, presumably, throws an error as well (didn't fire it up to check).

It seems to me that the errors and the confusion in JavaScript could be removed completely by simply putting the Equality operators at a lower precedence than the Bitwise operators.

I can't think of an instance where I want to have both a bitwise and an equality operation on the same line AND want to have the equality evaluated first.

Yet every programming language that I've checked shares the same order of operations.

What is the reason for this? Is there a common, legitimate, use that I am missing that makes it easier to have the precedence as designed?

5
  • Check the links I included, both logical and bitwise come after equality. (And I meant bitwise in this case, sorry for the confusion). Oct 10, 2014 at 16:01
  • It seems to be that your question is actually about bitwise operators, not logical operators. It seems sensible to put the logical operators after equality, think if(a == 2 && b == 2). The bitwise operators do seem a bit silly. Oct 10, 2014 at 16:09
  • 1
    "Languages have copied that from C, and for C, Dennis Ritchie explains that initially..." (answer in a duplicate question)
    – gnat
    Oct 10, 2014 at 16:15
  • errors and the confusion ... could be removed: The way to get rid of errors and confusion is for the programmer to use parentheses to make his intent unambiguous, e.g., ((2 & 15) === 2).
    – Blrfl
    Oct 10, 2014 at 16:50
  • Seems like this is a duplicate. My bad. I didn't spot it when writing the question. Oct 10, 2014 at 18:11

1 Answer 1

3

Legacy,

It used to be that in C the non-short circuiting logical operators were the only ones available and then it was logical for them to be after equality.

Later the short circuiting were created and the old precedence rule was never changed in the name of backwards compatibility.

3
  • I don't think C has non-short circuiting logical operators. Oct 10, 2014 at 15:45
  • @WinstonEwert the bitwise operators and have #define TRUE 1 and #define FALSE 0 Oct 10, 2014 at 15:50
  • okay, yeah. I never use those because I'm worried about what'll happen if something besides 1 or 0 gets in there. Oct 10, 2014 at 15:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.