#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

#76 – Arithmetic Operations with Small Integers

When doing arithmetic operations on variables of type byte, sbyte, short or ushort, the data values are first converted to int and the operations are performed on int types.

As an example, note that the following code does not compile.  You receive the compiler error “Cannot implicitly convert type ‘int’ to ‘byte’“.

 byte b1 = 5;
 byte b2 = 6;
 byte b3 = b1 + b2;

The problem is that the “b1 + b2” expression is evaluated as an int.  The two byte variables are first converted to int and the sum is calculated as an int.  But then we try to assign this int result back to a byte.  Because byte is smaller than int, we can’t do an implicit cast from int to byte.

We can avoid the compilation error by doing an explicit cast:

 byte b1 = 5;
 byte b2 = 6;
 byte b3 = (byte)(b1 + b2);