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

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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: SQL Recycle Bin Pattern - The Daily Six Pack: April 14, 2014

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: