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.
|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.
A whole slew of new power supplies to help bring your next project to life!
This post explores how to use the power control features of the Battery Babysitter to make a product with the features we expect from portable embedded electronics.
Let the countdown begin.
We present another set of concepts in the computer science series as they relate to Arduino.