On 2024-02-06, Lawrence D'Oliveiro <
[email protected]d> wrote:
Operator precedence in C, particularly in regard to the bitwise operators, can be a bit awkward. Consider an expression like
(val & check_bits) == set_bits
Yes, this is famous. It's because the bitwise & was used for combining
Boolean conditions, before && was introduced:
if (foo > 0 & odd(bar)) { ... }
In a 1982 e-mail, Dennis Ritchie wrote:
"In retrospect it would have been better to go ahead and change the
precedence of & to higher than ==, but it seemed safer just to split &
and && without moving & past an existing operator. (After all, we had
several hundred kilobytes of source code, and maybe 3 installations....)"
That's it. 600 kilobytes of code being preserved is why we can't have
val & check_bits == set_bits
and whatnot.
My question is, if this corresponding operator precedence change were to
be made in C, is there any actual real-world code that would break?
Yes; anything that does
some_condition & variable == TEST_VALUE
where && could have been used, but wasn't. Perhaps due to a typo;
but the code is tested and works since some_condition has the values
0 and 1.
A good time to fix it was when Dennis Ritchie and gang had 600 kilobytes
of code in 3 installations.
Yet, I think the situation could be repaired with a carefully
rolled-out plan.
Firstly, require all ambiguous uses of & to be parenthesized, so
that code like condition & variable == TEST_VALUE requires a diagnostic;
it has to be condition & (variable == TEST_VALUE) or
(condition & variable) == TEST_VALUE.
Then after a long period of obsolescence, remove the requirement for parentheses, and introduce the new precedence for & and |.
By the time the obsolescence period is over, most old code still in use
would have been fixed to have the required parentheses. Those are now
optional; new code can start using the nicer new precedence.
Then any remaining broken old code can still be supported with old
dialect modes, like "gcc -std=c17" or lower.
--
TXR Programming Language:
http://nongnu.org/txr
Cygnal: Cygwin Native Application Library:
http://kylheku.com/cygnal
Mastodon: @
[email protected]
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)