Next Previous Contents

8. Expressions are evaluated from left to right

Since cc65 is not building an explicit expression tree when parsing an expression, constant subexpressions may not be detected and optimized properly if you don't help. Look at this example:

      #define OFFS   4
      int  i;
      i = i + OFFS + 3;

The expression is parsed from left to right, that means, the compiler sees 'i', and puts it contents into the secondary register. Next is OFFS, which is constant. The compiler emits code to add a constant to the secondary register. Same thing again for the constant 3. So the code produced contains a fetch of 'i', two additions of constants, and a store (into 'i'). Unfortunately, the compiler does not see, that "OFFS + 3" is a constant for itself, since it does it's evaluation from left to right. There are some ways to help the compiler to recognize expression like this:

  1. Write "i = OFFS + 3 + i;". Since the first and second operand are constant, the compiler will evaluate them at compile time reducing the code to a fetch, one addition (secondary + constant) and one store.
  2. Write "i = i + (OFFS + 3)". When seeing the opening parenthesis, the compiler will start a new expression evaluation for the stuff in the braces, and since all operands in the subexpression are constant, it will detect this and reduce the code to one fetch, one addition and one store.


Next Previous Contents