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++:
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.
Operator | Meaning | Example |
---|---|---|
a += b | a = a + b | a += 3 |
a -= b | a = a - b | a -= 3 |
a *= b | a = a * b | a *= 3 |
a /= b | a = a / b | a /= 3 |
a %= b | a = a % b | a %= 3 |
a++ | a = a + 1 | a++ |
a-- | a = a - 1 | a-- |
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.