Operator Precedence and Associativity

Two characteristics of operators determine how they will group with operands:

precedence Precedence is the priority for grouping different types of operators with their operands.
associativity Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence.

For example, in the following statements, the value of 5 is assigned to both a and b because of the right-to-left associativity of the = operator. The value of c is assigned to b first, and then the value of b is assigned to a.

b = 9;
c = 5;
a = b = c;

Because the order of the expression evaluation is not specified, you can explicitly force the grouping of operands with operators by using parentheses. In the expression:

a + b * c / d

the * and / operations are performed before the + because of precedence. Further, b is multiplied by c before it is divided by d because of associativity.

Special Cases
Order of evaluation for function call arguments or for the operands of binary operators is not specified. Avoid writing ambiguous expressions, such as:

z = (x * ++y) / func1(y);
func2(++i, x[i]);

In the example above, the order of evaluation of ++y and func1(y) is not defined. In fact, they might not even be evaluated in the same order at different optimization levels. Do not write code that depends on a particular order of evaluation of operators that have the same precedence.

The order of grouping operands with operators in an expression containing more than one instance of an operator with both associative and commutative properties is not specified. The operators that have the same associative and commutative properties are *, +, &, |, and ^.

The order of evaluation for the operands of the logical AND (&&) and OR (||) operators is always left-to-right. If the operand on the left side of a && operator evaluates to a 0 (zero), the operand on the right side is not evaluated. If the operand on the left side of a || operator evaluates to a non-zero value, the operator on the right side is not evaluated.



Operator Precedence and Associativity Table