Skip to main content

Section 3.8 Arithmetic Operators

Subsection 3.8.1 Basics

Operators are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in C++ do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is + and multiplication is *.
The following are all legal C++ expressions whose meaning is more or less obvious:
1 + 1
hour - 1
hour * 60 + minute
Using the + and * operators, we can write a program that converts a time of day to minutes:
Listing 3.8.1.
In this program, hour * 60 + minute is an expression, which represents a single value to be computed (719). When the program runs, each variable is replaced by its current value, and then the operators are applied. The values that operators work with are called operands.
Expressions are generally a combination of numbers, variables, and operators. When evaluated, they become a single value. For example, the expression 1 + 1 has the value 2. In the expression hour - 1, C++ replaces the variable with its value, yielding 11 - 1, which has the value 10.
In the expression hour * 60 + minute, both variables get replaced, yielding 11 * 60 + 59. The multiplication happens first, yielding 660 + 59. Then the addition yields 719.
The value of an expression is temporary - if we donโ€™t do something with it, it will simply be discarded. That is why the sample above stores the value of hour * 60 + minute into the variable totalMinutes. We can also immediately print the result of an expression by doing something like: cout << 2 * x << endl; which would print out the result of multiplying x by 2.

Insight 3.8.1.

A variable on the left hand side of = is being written to. A variable on the right hand side of = or in any other expression is being read from. The entire right hand side of an assignment statement is evaluated to find a single value, which is then stored in the variable on the left hand side.

Subsection 3.8.2 Common Errors

Much of what you already know about math in other domains translates directly to C++. But there are a few common errors that come from assuming things that are not true in C++.
You may think of the โ€œ^โ€ symbol as meaning โ€œpowerโ€. It does not mean that in C++. It means โ€œbinary exclusive orโ€, an operation we will not cover. If you try to do something like 5 ^ 2 you will get an answer that has nothing to do with โ€œ5 to the second powerโ€. We will learn soon how to calculate exponents.
Another common mistake is to try to use โ€œimplicit multiplicationโ€. In math, we often write \(2x\) to mean โ€œ2 times xโ€. In C++ you always have to write out the *. Here are some samples:
Wrong Correct
2x 2 * x
2(x + 1) 2 * (x + 1)
(x2 - x1)(x2 - x1) (x2 - x1) * (x2 - x1)

Checkpoint 3.8.1.

You have attempted of activities on this page.