c2compiler icon indicating copy to clipboard operation
c2compiler copied to clipboard

Force parentheses use for same-priority expressions

Open bvdberg opened this issue 7 months ago • 4 comments

force use of parenthesis for unclear expressions: a < b < c a & 7 + 1

bvdberg avatar May 07 '25 06:05 bvdberg

force use of parenthesis for unclear expressions:

Yes this would help a lot. It is also a good alternative to changing the order of priority for the counter-intuitive choices in the C language, that have been kept in Java, Javascript and many more recent popular languages

a < b < c

This should evaluate as (a < b) < c, which does not make much sense.

An alternative would be to add new semantics such as (a < b) & (b < c), evaluating a, b and c once and only once. This would be very handy and allow multiple combinations of < and <= in the same expression. Of course the same should work for > and >= in combinations.

a & 7 + 1

For historical reasons, this evaluates as a & (7 + 1) in C, C++, C#, Java, Kotlin, Scala, Javascript, Perl...

Fixing this historical oddity by changing the order of priority is problematic as it complicates the porting of code from other languages. These expressions should be marked as errors with an explicit message such as

ambiguous operator precedence requires parentheses
    a & 7 + 1
      ^ ~~~~~

As an additional benefit, the expressions in the C backend would no longer require extra parentheses.

chqrlie avatar May 07 '25 09:05 chqrlie

An alternative would be to add new semantics such as (a < b) & (b < c)

Everyone who does this to C-like languages ends up regretting it.

lerno avatar May 07 '25 14:05 lerno

An alternative would be to add new semantics such as (a < b) & (b < c)

Everyone who does this to C-like languages ends up regretting it.

Then it is a bad idea.

Do you have pointers? Does any other language support such a thing ?

chqrlie avatar May 07 '25 14:05 chqrlie

I know of indie languages that did experiment with this. I don't recall the exact problems, but it was ambiguities and weirdness when combined with other operations. Also, from a C point of view it looks very foreign.

lerno avatar May 07 '25 14:05 lerno

implemented

bvdberg avatar Jun 26 '25 07:06 bvdberg