Adventures in Science: Arduino Arithmetic Operators

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

Favorited Favorite 1

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.


Comments 20 comments

  • EJLane / about 7 years ago / 1

    Just FYI, in your list of operations with bullet points, you have the wrong slash for division.

  • MatthewR / about 7 years ago / 1

    Since you listed =, it would be good to add a description for ==. For anyone who doesn't know, (a == b) will be true (or 1) if a is equal to b, otherwise it will be false (or 0). And you might as well add at least !, &&, and || (maybe also bit-wise operators). And again for anyone reading this who doesn't know, you can use these in assignments, not just for conditional statements.

    int a = 3;        // set a to 3
    int b = 10 / a;   // set b to 10 / 3 (which is 3 when using integer math)
    int c = (a == b); // c equals a==b, so since a and b are each 3, c is true or 1
    

    • Don't worry, I'm saving comparison and boolean operators for a future episode :)

    • MatthewR / about 7 years ago / 1
      false equals 0.
      true equals not 0 (typically 1 is used).
      ! means not. If 'a' is true, !a is false. If 'a' is false, !a is true.
      && means and. (a && b) will only be true if both 'a' and 'b' are true.
      || means or. (a || b) will be true if 'a' and/or 'b' is true.
      
      • Sembazuru / about 7 years ago * / 1

        true equals not 0 (typically 1 is used).

        Because true equaling not zero allows streamlining code. Lets say you want to do something with someRandomVariable only if that variable isn't zero. Then instead of writing:

        if (someRandomVariable != 0) {}
        

        you can short cut it and just write:

        if (someRandomVariable) {}
        

        for example:

        if (someRandomVariable)
        {
            Serial.println(5.0 / someRandomVariable);
        }
        else
        {
            Serial.println(F("Sorry, I don't have an ALU that can handle calculus so I can't divide by zero. Have a good day."));
        }
        

        Silly example, I know, but an example is an example.

        Even if that isn't your personal coding style, recognizing this would help understand other people's code.

  • dksmall / about 7 years ago / 1

    Can you spread out the columns in your table a little? At least in FireFox it's all running together as "OperatorMeaningExample". The examples are clumped together as well.

    • Should be fixed now; thanks for catching that! It looked right in my preview, but it seems that our blog isn't rendering markdown tables exactly right, so I made it a manual HTML table. Let me know if it still looks weird for you.

  • Member #394180 / about 7 years ago / 1

    You missed ++a and --a; They're the same as a++ and a-- except for when the operation occurs. The prefix operators happen before the variable is accessed, the postfix after.

    a = 5; b = a++;

    leaves a equal to 6 and b equal to 5.

    a = 5; b = ++a;

    leaves a and b both equal to 6.

    This lets you do some really slick stuff with loops and such.

    Edit - oops, sgrace beat me to it

    • Thanks! I rarely use the pre-increment statement, so I figured it was best left out for the sake of beginners. But yes, they are useful for doing some slick tricks in C/C++.

  • sgrace / about 7 years ago / 1

    A little "gotcha" the pre and post increment statements: http://stackoverflow.com/a/4706239

    • Definitely good tips to remember if you're trying to assign the output of the increment/decrement operators.

  • Member #394180 / about 7 years ago / 1

    One slick trick is to replace multiply and divide operators with the shift operators when the multiplicand and dividend are integers and the multiplier and divisor are powers of 2. In the good old days this would radically speed up the operation.

    These days, between crazy fast hardware and super-optimizing compilers, it's just a stunt to amaze and amuse (and sometimes confuse) your friends with. In fact. all good compilers now make the substitution for you, and in many cases, the hardware will do it if the compiler didn't.

    • Heh, I still do things like a = a << 1; to multiply by 2 knowing full well that modern compilers will optimize for that. Old habits die hard, I guess.

Related Posts

MicroMod Calendar

Recent Posts

Open-Source HVAC?

What is L-Band?

Tags


All Tags