#1,074 – Use Parentheses in Expressions to Make Code More Readable
April 14, 2014 3 Comments
In the absence of parentheses within an expression, operator precedence and associativity dictate how the expression will be evaluated. Technically, you only need parentheses in the expression if you want the expression to be evaluated differently, relative to the precedence and associativity rules.
If your expression doesn’t require parentheses in order to evaluate correctly, it’s often still a good idea to include them. The parentheses will typically improve the readability of the expression because they make the evaluation order more clear.
// This is tough to read int i5 = 1 + 10 / 5 * 2 - 12 / 4 + 24 % 5 / 2 * 4; // This is a bit better i5 = 1 + ((10 / 5) * 2) - (12 / 4) + (((24 % 5) / 2) * 4);
Pingback: DotNet Explained - The Daily Six Pack: April 15, 2014
General rule: if you have to look at an operator precedence chart to find out if you need parens or not, you need parens.
Agreed. And use them even more often than that.