Adventures in Science: Arduino Arithmetic Operators

How to use the various math operators and compound assignment operators in C/C++.

Building on data types and literals from last week, we look at how we can add, subtract, multiply and divide literals and variables in C and C++ (specifically, in the Arduino environment).

There are six main arithmetic operators in C and C++:

  • = is the assignment operator. It does not necessarily show equality but is used to set values to variables.
  • + is for addition. You can add two numbers or values in variables together.
  • - is subtraction, and it is used to subtract one number from another.
  • * is multiplication for multiplying two numbers together.
  • / is division. Note that when using integers, you don't get fractions or a remainder from this operation.
  • % is the modulo operator, and it is used to get the remainder from a division operation.

If you need a fractional result from division, you can use the float data type. If you're using literals to perform the division, make sure you add some kind of decimal to one of the numbers. For example, 19 / 5 should be 19.0 / 5.

To make writing and reading code easier, you can use compound assignment operators. These perform some math operation on a variable and then store the result back in the same variable.

OperatorMeaningExample
a += ba = a + ba += 3
a -= ba = a - ba -= 3
a *= ba = a * ba *= 3
a /= ba = a / ba /= 3
a %= ba = a % ba %= 3
a++a = a + 1a++
a--a = a - 1a--

The Arduino Reference Guide is still a good place to see which operators the Arduino supports.

While this video is intended as a reference for beginners, what slick tricks have you used or seen with operators? Any tips for good overloading practices? Please share your thoughts in the comments below.