## #1,073 – Arithmetic Binary Operators are Left-Associative

April 11, 2014 1 Comment

All arithmetic binary operators (+, -, *, /, %) are left-associative. This means that when there are multiple operators having the same precedence, the expression is evaluated from left to right. Below are some examples.

// Multiplicative, left-right // (10 / 5) * 2 = 4 // [result would be 1 if right-associative] int i = 10 / 5 * 2; // (40 % 12) * 2 = 8 // [result would be 16 if right-associative] int i2 = 40 % 12 * 2; // Additive, left-right // (4 - 3) + 5 = 6 // [result would be -4 if right-associative] int i3 = 4 - 3 + 5;

Note that the multiplicative operators (*, /, %) have a higher precedence than the additive (+, -). This means that if there are no parentheses, the multiplicative operators are evalated before the arithmetic.

// 1 + (2 * 3) = 7 int i4 = 1 + 2 * 3; // Equivalent to 1 + ((10 / 5) * 2) = 5 int i5 = 1 + 10 / 5 * 2;

Advertisements