C Sharp

Practical Usage

Nothing is more insidious than tracking down a bug for a long period of time only to find that the bug resulted from a developer not knowing the rules of precedence or associativity. I've seen several posts on mailing lists in which intelligent people have suggested a programming convention whereby spaces are used to indicate which operators they think will have precedence, a kind of self-documenting mechanism. So, for example, because we know that the multiplication operator has precedence over the addition operator, we could write code similar to the following where white spaceindicates the order of intended precedence: -

a = b*c + d;

This approach is severely flawed-the compiler doesn't parse code properly without specific syntax. The compiler parses expressions based on the rules determined by the people that developed the compiler. To that end, a symbol exists that allows you to set precedence and associativity: the parenthesis. For example, you could rewrite the expression a = b * c + d as either a = (b * c) + d or a = b * (c + d), and the compiler will evaluate what's in the parentheses first. If two or more pairs of parentheses exist, the compiler evaluates the value in each pair and then the entire statement by using the precedence and associativity rules I've described.

My firm opinion is that you should always use parentheses when using multiple operators in a single expression. I'd recommend this even if you know the order of precedence because the folks who maintain your code might not be as well informed.

by BrainBellupdated
Advertisement: