On 27/11/2021 10:50, Rod Pemberton wrote:
> Do you understand how a C expression is parsed without the parentheses?
> I don't. I've been programming C for three decades. Without the
> parentheses, I have to look up the precedence rules in a table in a
> book, largely because they're not what I would expect and there are too
> many of them to easily remember. In general, C programmers add extra
> parens, because no one knows what those rules are, especially since
> most C programmers don't have the correct book, or any book for that
> matter, nor the C standard available.
>
Most people have the internet available these days. It is not hard to
google for C operator precedence rules.
(It's not hard to find the free draft versions of the C standards
either, but that does not make them easy to read!)
A good reference for C is :
<
https://en.cppreference.com/w/c>
The same site also has C++, and it is recommended and supported by the C
and C++ groups at ISO. It is a reference, not a tutorial, but worth
bookmarking for any C or C++ programmer.
And a good online compiler is a great resource for learning or testing
code. <
https://godbolt.org> has a wide selection of compilers and
programming languages - I use it regularly in my work.
In the particular case of parenthesis and operator precedence, I think
the common operators are easy to remember, and are reasonably logical.
It gets harder with the rarer ones - primarily because you don't
remember things you don't use much.
I'm a fan of adding extra parenthesis, as long as they serve a purpose -
I write:
(x >= 10) && (x < 20)
To me, the only reason to write that without parenthesis would be to
brag about how the writer knows all the precedence rules. It is simply
clearer to group logical parts of an expression, and parentheses help
there - it's all clearer to the reader.
Local variables are free. Large expressions can be broken up in
separate lines with separate parts. This gives you more room, lets you
use names, lets you be clear about types, gives you place to add
comments explaining the purpose of the expressions, and makes it all
easier to maintain and friendlier for source code management, change
management and code reviews.
(This applies to all languages, of course, not just C.)