#167 Check for parentheses to disambiguate precedence

Check (274)
Dale King

I am of the position that one should not be too intimate with
the precedence table for the language. There are
expressions where it is not completely obvious how an
expression will be evaluated based on the precedence of
two operators. One can certainly look it up or have
memorized the precedence table so that you actually code
it correctly, but will the next person reading the code get it

I, in fact, actually advocating intentionally not knowing the
precedence of certain operations. If you aren't sure then
you will use parentheses to make it explicit instead of
relying on the precedence table. What I propose is a way
to specify in a check a way to implement specific
ignorance of the precedence table and requiring that
parenthese be used.

For example take this expression:

a & 0xFF >> 8

Which of the following is that equivalent to (without looking it

( a & 0xFF ) >> 8
a & ( 0xFF >> 8 )

The answer is the latter, which means this expression
always evaluates to zero. What was probably meant was the

What I want is a check that reports cases like this where I
do not use parentheses and leave it up to the precedence

But there are cases that should not need parentheses. For
instance the precedence of + and * are well established
from mathematics so the following expression should be OK:

a * b + c

So it needs to be configurable in what is acceptable and
what is not. The way I envision it is that you specify pairs of
operators that must be explicitly disambiguated with
parentheses. This could be a long list.

This also can work for associativity by simply specifying the
same operator for both parts of the pair.

Some issues to consider are the ?: is like 2 operators. Cast
and '.' should be considered as operators here too.


Log in to post a comment.