#1,074 – Use Parentheses in Expressions to Make Code More Readable

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);
Advertisements

#514 – Examples of Operator Precedence

Each operator has an associated precedence, which indicates the order in which the operators are evaluated when evaluating the  expression.

For example, because multiplicative (*, /, %) operators have a higher precedence than additive (+, -) operators, the multiplication in the expression below happens before the addition, so the answer is 34.

int result = 4 + 5 * 6;

If we want the addition to happen first, we can change the precedence by using parentheses.

// Result = 54
int result = (4 + 5) * 6;

Here are some other examples of operator precedence.

            // Negation operator has higher precedence than conditional operators
            bool res = !false || true;    // true  (negation operator evaluated first)
            res = !(false || true);       // false (conditional OR evaluated first)

            // && has higher precedence than ||
            bool res = true || false && false;    // true
            res = (true || false) && false;       // false