Is there ANY chance we can fix the bitwise operator precedence rules?

Robert Jacques sandford at jhu.edu
Fri Jun 18 19:46:29 PDT 2010


On Fri, 18 Jun 2010 17:03:24 -0400, Don <nospam at nospam.com> wrote:

> In the comments for bug 4077, "Bugs caused by bitwise operator  
> precedence"
> it was asked why C gave & with lower precedence than ==, when it is  
> unintuitive and a frequent source of bugs.
>
> I was quite shocked to find that the reason is backwards compatibility  
> with the B programming language.
>
> Denis Ritchie says (http://cm.bell-labs.com/cm/cs/who/dmr/chist.html):
> --------------------
> At the suggestion of Alan Snyder, I introduced the && and || operators  
> to make the mechanism [[short circuit evaluation]] more explicit.
>
> Their tardy introduction explains an infelicity of C's precedence rules.  
> In B one writes
>
>      if (a==b & c) ...
>
> to check whether a equals b and c is non-zero; in such a conditional  
> expression it is better that & have lower precedence than ==. In  
> converting from B to C, one wants to replace & by && in such a  
> statement; to make the conversion less painful, we decided to keep the  
> precedence of the & operator the same relative to ==, and merely split  
> the precedence of && slightly from &. Today, it seems that it would have  
> been preferable to move the relative precedences of & and
> ==, and thereby simplify a common C idiom: to test a masked value  
> against another value, one must write
>
>      if ((a&mask) == b) ...
>
> where the inner parentheses are required but easily forgotten.
> -----------------------------------
> Tragic. Can we end this madness?
>
> Could we give & | ^ the same precedence as ==, making
> (a & mask == b) an error, just as (a < b == c) is rejected?
> That way we could lay this common bug to rest. I've personally lost days  
> of my life to this one. It's a bug 100% of the time.
>
> Or is too late to break backwards compatibility with B ?
>
> BTW I think this a great cautionary tale about the dangers of rating  
> backwards compatibility too highly.

Well, you've got a big vote++ from this a & mask == b bug survivor. I also  
think your solution is simple and elegant.


More information about the Digitalmars-d mailing list