Almost every sketch uses mathematical operators to manipulate the value of variables. This chapter provides a brief overview of the most common mathematical operators. As the preceding chapter is, this summary is primarily for nonprogrammers or programmers who are not familiar with C or C++. For more details, see one of the C reference books mentioned in the Preface.

You want to perform simple math on values in your sketch. You want to control the order in which the operations are performed and you may need to handle different variable types.

Use the following code:

int myValue; myValue = 1 + 2; // addition myValue = 3 - 2; // subtraction myValue = 3 * 2; // multiplication myValue = 3 / 2; // division (the result is 1)

Addition, subtraction, and multiplication for integers work much as you expect.

Make sure your result will not exceed the maximum size of the destination variable. See Recipe 2.2.

Integer division truncates the fractional remainder in the
division example shown in this recipe’s Solution; `myValue`

will equal 1 after the division (see
Recipe 2.3 if your application
requires fractional results):

int value = 1 + 2 * 3 + 4;

Compound statements, such as the preceding statement, may appear
ambiguous, but the *precedence* (order) of every operator is well defined. Multiplication and division have a higher precedence than addition and subtraction, so ...

Start Free Trial

No credit card required