c programming tips and tricks

Parentheses – to use or not to use?

A competent and experienced C programmer will neither overuse nor underuse parentheses-the round bracket delimiters “(” and “)”. But what exactly is the correct way to use parentheses?

There are a number of simple rules:

1) To change the normal operator precedence.
For example, 3 * (4 + 3) is not the same as 3 * 4 + 3 .

2) To make things clearer. It isn’t absolutely necessary to use parentheses here:

t = items > 0 ? items : -items;

That’s because the operator precedence of || is lower than < and >. However, you might find it clearer to write this:

(x > 0) || (x < 100 & y > 10) || (y < 0)

Using parentheses for clarity is useful because not many people can correctly list all the C operator priorities.

3) In a macro expression. It is a good idea to add parentheses when defining a constant like this:

#define MYCONST (4 + 3)

That’s because you don’t know where this constant might be used. In the example above, if there were no parentheses, you may not get what you expect. Consider this:


The resulting value would be different (due to the effects of operator precedence) if you omitted the parentheses in the constant declaration.

But there’s one place where you don’t need to use parentheses: in a return statement. For example, this…

return (x + y);

…has exactly the same effect as

return x + y;

Many programmers make a habit of using unnecessary parentheses in return statements. This may be because they are used to placing expressions between parentheses in other control statements such as if, while, for, and do. All of those statements require parentheses. But a return statement does not.

Leave a Reply

Your email address will not be published. Required fields are marked *