top | item 38890477

(no title)

goto11 | 2 years ago

Thank you for this additional context.

So in short, bitwise operators have lower precedence than comparisons to allow you to write:

    if (a==b & c==d) ...
but of course, this means you can't write bitwise checks like this:

   if (addr & mask == 0) ...
The problem could theoretically have been solved when the shortcut operators were introduced, by increasing the precedence of & and | to be higher than comparisons, but have the shortcut operators be lower. So you would be able to write both:

   if (a==b && b==c) ...

   if (addr & mask == 0) ...
But this was not done due to concerns of backward compatibility with existing code, since now every expression using the old pattern would subtly change semantics. E.g. the first example would now be parsed as:

  if ((a==(b & c))==d) ...

discuss

order

MaxBarraclough|2 years ago

> you could write [...] but of course, this means you can't write

I found this rather difficult to read. You could write those expressions. They're legal C code. Whether they will have the expected semantics will depend on, well, what you expected.

The more general problem is code that relies too heavily on precedence rules in the first place. Precedence-related bugs and readability issues are easily avoided, just use parentheses. As I mentioned in another comment in this thread, some languages force the programmer to do this.

goto11|2 years ago

Sure, you can use parentheses everywhere, but the code would be quite noisy. Do you think this:

  ((window.location).href) == foo;
is more readable than:

  window.location.href == foo;

leereeves|2 years ago

Why was it important to allow you to write:

    if (a==b & c==d)
I always thought using the bitwise operator as if it were a logical operator was simply a mistake, even though it works because false is 0 and true is 1.

Edit: Mea culpa for reading and responding to the comments before the article.

blixt|2 years ago

Because before there was && the & was used to mean the same as && does today. This happened when the context was Boolean such as an if.

rcxdude|2 years ago

I think at that point in C's development && and || did not exist: the bitwise were the only options.