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 *.
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.
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.
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: