Home > Computing > Operator precedence

Operator precedence

Recently I came a cross a bug where the author forgot to use parentheses in a conditional expression. The code went like this:

if (AAA &&
    BBB || CCC || DDD)
    /* ... */

The bug was obvious, because this is what the author really meant:

if (AAA && (BBB || CCC || DDD))

But this is not how compiler understood it.

There are so many operators, that it’s hard to remember their precedence. Not many people remember immediately whether | (bitwise or) operator has higher or lower precedence than & (bitwise and) or ^ (bitwise xor). Let alone the << and >> (bitwise shift) operators, which in C++ are used as stream operators, and have higher precedence than other bitwise operators. There are also other surprises, such as comparison operators having a higher precedence than bitwise and/or/xor operators.

These days its not uncommon to use more than one language in everyday life, especially various scripting languages come to mind. Many languages share the set of operators, but operator precedence may vary between languages, for example Python’s operator precedence is different than C’s.

All this results in errors when writing code and creates unnecessary maintenance problems.

There are several groups of operators which have obviously higher precedence than others. For example * (multiply) operator has higher precedence than + (add) operator, we were taught this on mathematics lessons in elementary school. Also it’s not a surprise than arithmetic operators have higher precedence than logical operators. But other combinations are ambiguous. Should bitwise operators have higher or lower precedence than arithmetic operators?

To avoid bugs and make the code easier to read for anybody who will be maintaining or extending it, it is a good practice to use parentheses. It’s good to have this rule in coding conventions for any project.

Languages should impose the usage of parentheses in ambiguous situations in their grammars. It is easy to define such grammar rules even in the simplest notations like BNF. For example such rule would forbid mixing various bitwise operators without parentheses or mixing arithmetic and bitwise operators, etc. This would help to avoid subtle bugs which are sometimes difficult to spot.

Categories: Computing
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: