#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
Advertisement