Next

Brackets Off!

Thomas Guest


Table of Contents

Introduction
More Examples
Coding Standards and Guidelines
Concluding Thoughts
References

Introduction

The mathematical formula:


v = u + at

calculates the speed, v, of an object, with initial speed u and constant acceleration a, after time t. Placing the a next to the t is a convenient shorthand for multiply a by t, which also makes it apparent that the multiplication must be done before the addition.

When the same formula is written in C, the multiplication operator needs explicit representation:


v = u + a * t

The layout of this expression no longer makes it clear that the multiplication should be done before the addition, so a programmer might choose to parenthesise:


v = u + (a * t)

Are these parentheses required to guarantee correct evaluation of v? If not, should they be included anyway, to help convey the meaning of the expression? How can coding standards help with such choices?

This article aims to answer these questions. It first presents some examples of the operator precedence and associativity rules in action, then offers some guidelines on when to parenthesise expressions, and finally argues that these guidelines should be replaced by a single rule.


Next